Date and time to milliseconds in Android - android

I am trying to convert given date and time to milliseconds. I am not able to achieve it.
Below is the format of date and time
02 - 07 (DD - MM)
08:50:00 AM (hh mm ss a)
Here is what I have tried:
String myDate = "2-05";
String myTime = "08:50:00";
String ampm = "AM";
String toParse = myDate + " " + myTime+" " + ampm;
try
{
SimpleDateFormat formatter3 = new SimpleDateFormat("d-M hh:mm:ss a"); // I assume d-M, you may refer to M-d for month-day instead.
Date date;
date = formatter3.parse(toParse);
long millis = date.getTime();
Log.e ("Date in milli",""+millis);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} // You will need try/cat
Below is the error I am getting:
08-04 16:50:34.368: W/System.err(6603): java.text.ParseException: Unparseable date: "2-05 08:50 AM"
08-04 16:50:34.368: W/System.err(6603): at java.text.DateFormat.parse(DateFormat.java:626)
Not sure where I am going wrong? Can somebody help me out ?
Thanks!

There is a difference between the exception you're getting and the date you're supplying in the code. The exception says the provided string is 2-05 08:50 AM, but you should be providing the seconds field as well. It should be 2-05 08:50:00 AM is there a mismatch somewhere? Are you running old code?
As others have identified, if your month is always two digits, you need to use MM instead of M

Related

How to format this incoming timestamp String from server?

I'm receiving this Timestamp string from the server:
"timestamp": "2021-02-21T22:15:37.672+00:00" I'm not sure what format it's in
how I can format it to a Month day time format such as February 21st, 4:00pm?
Edit:
Using the answer below:
String time = "2021-02-21T22:15:37.672+00:00";
try {
Date dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").parse(time);
Log.d(TAG, "onCreate: " + dateFormat.toString());
} catch (ParseException e) {
e.printStackTrace();
}
"2021-02-21T22:15:37.672+00:00" is "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" in SimpleDateFormat in JAVA SE7.
"February 21st, 4:00pm" is "MMM dd, h:mma"
The "st" part seems like it have to be determine manually in SimpleDateFormat.
SimpleDateFormat
That most likely is UTC time. You can tell it is because it doesn't have an offset via the +00:00, which is used for timezone offset. UTC can be converted to other timeszones using DateFormat.
Ref:
https://developer.android.com/reference/java/text/DateFormat

How to covert string data like 2016-4-10 00:00:00 to timestamp?

I want convert data like 2016-4-10 00:00:00 to timestamp.
I use this code (I send this date as argument to this method):
public static long parseUTimeAndGiveTimestamp(String time) {
if (time != null && !time.equals("")) {
long longTime = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS");
Date date;
try {
time += ".000";
date = sdf.parse(time);
} catch (Exception e) {
e.printStackTrace();
return longTime;
}
longTime = date.getTime();
return longTime / 1000;
}
return 0;
}
But I get 1460235600 value and if I convert it to date again I get:
Sat, 09 Apr 2016 21:00:00
(before 10.04 - after 09.04)
So you can help me?
There is no issue with your code. There is some issue with the timezones. Your SimpleDateFormat will be using your local timezone. You probable might be getting the timestamp for your locale and while converting it back to the date, you are checking in GMT timezone. To test this just add
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
before parsing the date.
So basically you are not using the same timezones to convert date to timestamp and while converting timestamp to zone.
try to use one M to parse single-digit month format. It also handles two-digits correctly...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd kk:mm:ss.SSS");

date is null and crashing on a few devices

I am using the this code to convert date time to unixtime gmt . It is working fine on most of the devices but it is crashing in a few . I am unable to determine the cause. How can I fix it ?
int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
String dt="11-01-2016 5:8 AM";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
try {
date = format.parse(dt);
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
long unixtime = (date.getTime() -(gmtOffset))/1000;
error:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
When the locale is not set to US English, the locale's Am/pm marker may be different. For example, in Chinese, the AM/PM maker will be 上午/下午.
Thus, to force use of AM/PM, you'd need to use a US date format:
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.US)
I ran this code when in the US locale, and it worked fine. When I switched to Chiense, I got the message:
java.text.ParseException: Unparseable date: "11-01-2016 5:8 AM" (at
offset 15)
Offset 15 is the AM/PM marker. Thus, when exiting the try/catch block, the date object will remain null, causing the NullPointerException when calling the getTime() method.
By the way, you might consider using Joda DateTime to get the Unix epoch, something along the lines of: Joda DateTime to Unix DateTime.
Maybe the dtStart doesn't have the same format always (in this case it is hardcoded). If the format of dtStart is not correct after try catch block "date" is null and the app crashes at the last line because the date is null. (date.getTime())
The exception is throw when date is null.
And date will be null if dtStart can't be parsed.
Try like this:
int gmtOffset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
String dtStart="11-01-2016 5:8 AM";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
long unixtime = 0;
try {
date = format.parse(dtStart);
System.out.println("Date ->" + date);
unixtime = (date.getTime() -(gmtOffset))/1000;
} catch (Exception e) {
e.printStackTrace();
}

Local time to EST time Conversion

Android Local time to EST time Conversion
Code:
SimpleDateFormat serverDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
serverDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar calender= Calendar.getInstance(Locale.getDefault());
String time=serverDateFormat.format(calender.getTime());
but i getting wrong time.
one hour difference from right time.
for eg :
local time : Tue Jul 07 17:30:00 GMT+05:30 2015
formated time : 2015/07/07 07:00:00
right time : 2015/07/07 08:00:00
Your problem is using the identifier "EST" which stands for "Eastern Standard Time". As the name suggests it does not use daylight saving rules. Proof:
TimeZone tz = TimeZone.getTimeZone("EST");
long offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: EST:false/-5
Use the timezone id "America/New_York" instead:
tz = TimeZone.getTimeZone("America/New_York");
offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: America/New_York:true/-4
Then you will observe daylight saving time in July making an offset difference of (+05:30) - (-04:00) = +09:30 resulting in the expected local time 8 AM.
hey please try this function for time conversion -
public static String getTime(String time, SimpleDateFormat sdf) {
String convertedTime = "";
try {
TimeZone timeZone = TimeZone.getDefault();
Date postdate = sdf.parse(time);
long postTimeStamp = postdate.getTime() + timeZone.getRawOffset();
String dateString = sdf.format(new Date(postTimeStamp));
convertedTime = dateString;
// convertedTime = getLastTime(context, time);
} catch (Exception e) {
e.printStackTrace();
}
return convertedTime;
}

How to convert current date and time format in milliseconds (only 10 digits)?

I have converted date format in milliseconds and time format in milliseconds. I am getting current time in more than 13 digits. CurrentTime= 1357755780000, StartingTime=1357602840, EndingTime=1357756140
But when I do comparison in below code, the if part is not executed, only the else part is executed.
Is there any mistake in my code? I want to make currentTime in 10 digits. So I think, conversion of date format to milliseconds is wrong.
String toParse = getDateorTime(1) + " " + getDateorTime(2);
long currentTime=0,startingTime=0,endingTime=0,milliseconds=0;
try
{
dateFormater = new SimpleDateFormat("yyyy/MMM/dd hh:mm");
Date date = null;
try {
date = dateFormater.parse(toParse);
date.setTime(milliseconds);
}catch (Exception e) {
System.out.println("\n Error in date parsing"+e.toString());
}
currentTime = (date.getTime());
start=Long.parseLong((cursor.getString(5).trim()));
end=Long.parseLong((cursor.getString(6).trim()));
}catch (ParseException pe) {
pe.printStackTrace();
}
if((currentTime>=startingTime)&&(currentTime<=endingTime))
{
//
}
Based on your examples, you actually have startingTime and endingTime in SECONDS, while you're comparing it to currentTime in MILLISECONDS. Simply multiply the second-times by 1,000, like so:
if((currentTime>=startingTime*1000L)&&(currentTime<=endingTime*1000L))
Simply divide by 1000
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeInMillis()/1000);
Convert the long values to string and if length is >10 simply substring the value (0,10) and then you can use string .equals too or covert them back to long for comparison .

Categories

Resources