So I am trying to parse a date string in Java. I am getting the correct hours back but the minutes seem to be out by about 5-10. I am showing my code below along with the input string and the date Objects toString() output.
Any ideas where I am going wrong? This is on Android so I would prefer not to use JodaTime.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
Date date = sdf.parse(input);
return date;
Input String = 2012-11-07T12:47:05.0581816Z
Date toString() = Wed Nov 07 12:56:46 GMT 2012 (Milliseconds = 1352293006816)
You are trying to parse a date with microsecond precision as millisecond precision.
0581816 is the number of milliseconds added to the time 12:47:05, not, as you probably expect, a decimal fraction of a second.
Since the precision below millisecond cannot be represented by java.util.Date, the simplest option would be to truncate the decimal fraction and adjust the date format, as follows:
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = "2012-11-07T12:47:05.058234234Z";
input = input.replaceFirst("(?<=\\.\\d{3})\\d+", "");
System.out.println(input);
System.out.println(sdf.parse(input));
Please make sure you are using the same time zone while converting a String to a date object and vice-versa
Related
I am running below snippet and I am getting inconsistent resluts
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSS");
System.out.println(outputFormat.format(date));//06-30-20 11:45:45. 123 is the output
Snippet 2:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123456");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSS");
System.out.println(outputFormat.format(date));//06-30-20 11:47:48. 000456 is output
snippet 3:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M-dd HH:mm:ss.SSSSSSSSS");
Date date;
date = inputFormat.parse("2020-6-30 11:45:45. 123456789");
SimpleDateFormat outputFormat = new SimpleDateFormat("MM-dd-yy hh:mm:ss. SSSSSSSSS");
System.out.println(outputFormat.format(date));//07-01-20 10:03:21. 000000789 is output
I believe the fraction seconds should be same before and after conversion. How can I achieve consistent results
The first one is correct, because your milliseconds are between 0 - 999. The second and third one are technically also correct, except your 123456 milliseconds are converted in 123 seconds + 456 milliseconds, which results in a time of +2 mins 03 secs.
So instead of trying to fix the output of simple date format, you have to fix the way you handle the input. Simple date format can not parse anything smaller than milliseconds. If you provide it with a number bigger than 999 milliseconds, it affects the seconds and so on...
I have a time stamp like this(form a json response) :
"/Date(1479974400000-0800)/"
I'm trying this function to convert time stamp into date:
public String getDate() {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
How to convert this Timestamp into Date format?
Parse directly into an OffsetDateTime
Java can directly parse your string into an OffsetDateTime. Use this formatter:
private static final DateTimeFormatter JSON_TIMESTAMP_FORMATTER
= new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendOffset("+HHMM", "Z")
.appendLiteral(")/")
.toFormatter();
Then just do:
String time = "/Date(1479974400000-0800)/";
OffsetDateTime odt = OffsetDateTime.parse(time, JSON_TIMESTAMP_FORMATTER);
System.out.println(odt);
Output is:
2016-11-24T00:00-08:00
In your string 1479974400000 is a count of milliseconds since the epoch of Jan 1, 1970 at 00:00 UTC, and -0800 is an offset of -8 hours 0 minutes from UTC (corresponding for example to Pacific Standard Time). To parse the milliseconds we need to parse the seconds since the epoch (all digits except the last three) and then the millisecond of second (the last three digits). By specifying the width of the milliseconds field as 3 Java does this. For it to work it requires that the number is at least 4 digits and not negative, that is not within the first 999 milliseconds after the epoch or earlier. This is also why I specify in the formatter that the seconds must not be signed.
I specified Z for offset zero, I don’t know if you may ever receive this. An offset of +0000 for zero can still be parsed too.
Original answer: parse the milliseconds and the offset separately and combine
First I want to make sure the timestamp I have really lives up to the format I expect. I want to make sure if one day it doesn’t, I don’t just pretend and the user will get incorrect results without knowing they are incorrect. So for parsing the timestamp string, since I didn’t find a date-time format that would accept milliseconds since the epoch, I used a regular expression:
String time = "/Date(1479974400000-0800)/";
Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
Matcher m = pat.matcher(time);
if (m.matches()) {
Instant i = Instant.ofEpochMilli(Long.parseLong(m.group(1)));
System.out.println(i);
}
This prints:
2016-11-24T08:00:00Z
If you want an old-fashioned java.util.Date:
System.out.println(Date.from(i));
On my computer it prints
Thu Nov 24 09:00:00 CET 2016
This will depend on your time zone.
It is not clear to me whether you need to use the zone offset and for what purpose. You may retrieve it from the matcher like this:
ZoneOffset zo = ZoneOffset.of(m.group(2));
System.out.println(zo);
This prints:
-08:00
The zone offset can be used with other time classes, like for instance OffsetDateTime. For example:
OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
System.out.println(odt);
I hesitate to mention this, though, because I cannot know whether it is what you need. In any case, it prints:
2016-11-24T00:00-08:00
If by date you mean Date instance, then you can do this:
new Date(Long.parseLong("\/Date(1479974400000-0800)\/".substring(7, 20)));
I assume this info in holding the String representing an Epoch and a TimeZone
"/Date(1479974400000-0800)/"
you need to get rid off the all the not necessary parts and keeping only the
1479974400000-0800
then the epoch is 1479974400000 and I guess the Timezone is 0800
then do:
String[] allTimeInfo = "1310928623-0800".split("-");
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
Date time = new java.util.Date(Long.parseLong(allTimeInfo[0]));
System.out.println(time);
System.out.println(timeZoneFormat.format(time));
The solution works
for me is like this:
String str = obj.getString("eventdate").replaceAll("\\D+", "");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new java.util.Date(Long.parseLong(upToNCharacters));
// System.out.println(time);
model.setDate(String.valueOf(timeZoneFormat.format(time)));
Use time variable where you want
I have unix timestammp stored in mysql. I am converting it into time. It displays wrong time.
Here is code:
Date date = new Date((long)timestamp*1000);
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
timeString = sdf.format(date);
System.out.println(timeString);`
timestamp is variable which contains unix timestamp.
Ex: for timestamp=1417437428505 it should show 6:07 PM and showing 12:31 AM
What is solution for it?
You're multiplying a timestamp which is already in milliseconds since the Unix epoch by 1000. You just want:
Date date = new Date(timestamp);
If you look at all of the date, not just the time, you'll see it's currently in 46886!
Are You sure that need multiplied by 1000? I tried pass without multiplying Date date = new Date(timestamp); and it printed 6:07 PM
Remove multiply with 1000 in
Date date = new Date((long)timestamp*1000);
than it works.
I'm running the program written below, but instead of printing in mm/dd/yyyy hh:mm format it prints in the normal date format(ie. Day Date and time)
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy hh:mm");
Date date = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
The reason i'm doing this is because the existing method accepts parameters in Date format, so i need to send the above mentioned date object to it.
Please point out the mistake or suggest some other alternative.
Thanks
Date objects don't have a format. The Date class is a wrapper around a single long, the number of milliseconds since the epoch. You can't "format" a Date, only a String. Pass around a Date/Calendar internally, and format it whenever you need to display it, log it, or otherwise return it to the user.
Change the format to MM/dd/yyyy. Month is denoted by capital M.
Check below URL for valid formats
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your formatter works quite fine (apart from the mm vs. MM bug). You get a formatted string from the date and then create a copy from your date by parsing the formatted string:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date now = Calendar.getInstance().getTime();
String formattedNow = sdf.format(now); // == "09/24/2013 01:59"
Date now2 = sdf.parse(formattedNow); // == now
I want to get the difference between two times. I.e., current time and time1 (like "17 Jun 2011 01:59:25"). By one way, we can do by using Date(string). But it is deprecated method. How to do this with a non-deprecated method?
Use java.text.SimpleDateFormat to parse a string into a Date object. For example:
String text = "17 Jun 2011 01:59:25";
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Date date = df.parse(text);
You can get the time difference between two Date objects by calling getTime() on them and subtracting the values:
Date now = new Date();
long diff = now.getTime() - date.getTime();
System.out.println("Time difference in milliseconds: " + diff);
If you want to know the difference in seconds, minutes, hours, etc. then divide the number of milliseconds by the appropriate factor.
There is comment on deprecated tag
replaced by DateFormat.parse(String s)