I have a JS date that is being converted by Dojo into RFC822 format. The function call -
dojo.date.toRfc3339(jsDate), generates the following date - 2007-02-26T20:15:00+02:00.
I have an application that uses a Java date SimpleDateFormat to parse in the dates generated above. I am having problems parsing this date format due to the timezone. I have attempted to use
yyyy-mm-DD'T'hh:mm:ssZ
This fails as the 'Z' for timezone doesn't expect a ':' character. Does anyone know how I would specify a pattern to handle a RFC822 date with the ':'?
revision:
Thanks for correctly interpreting what I am trying to do :) I was meant to say the date is generating in RFC3339 and I needed RFC822. Looks like I will have to override the JavaScript. I was hoping that I wouldn't have to do that and could specify a date format pattern without having to modify any Java Code as the date format is simply injected into a Spring bean of an application.
Just for completeness, is there a way to specify in a date format expression to ignore characters in the sequence (without doing String manipulation/replacement)? In this case I'd be saying ignore any ':' or just ignore the timezone all together?
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static Date ParseRFC3339DateFormat(String p_date)
{
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String dts = p_date.replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2");
return formatter.parse(dts);
}catch (Exception e) {
return null;
}
}
}
This works
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-DD'T'hh:mm:ssZ");
format.parse("2007-02-26T20:15:00+02:00".replaceAll("([\\+\\-]\\d\\d):(\\d\\d)","$1$2"));
(Note I've taking the final colon out of the format after the 'Z' format specifier.)
RFC822 does not allow a colon to be in the time zone portion of date. It expects just the 4 digits. The name of that Dojo method indicates that it is using RFC3339. It seems that is practically the same format as ISO8601. It just so happens that Joda Time has ISODateTimeFormat which is ISO8601 compatible if you are able to use that library. The method dateTimeNoMillis() looks like a match with the Dojo format. It really is nicer than the standard Java date and time API. Otherwise highlycaffeinated's suggestion would be the way to go.
Updated in response to Jamen's update
Isn't there a way to have Dojo use a format that doesn't include the timezone? Then you can adjust the format on the Java side to match. I don't know much about Dojo and I haven't been able to find any documentation on the toRfc3339 function it provides.
In Java 8 you can use:
Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse( rfc822Time ) );
FYI: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#RFC_1123_DATE_TIME
I'd strip the ':' out of the timezone and use the format you have above.
Instead of using dojo.date.toRfc3339(jsDate) you could create your own function with a custom format string.
Something like the following would remove the colon and should be parsable by your java format.
function toRfc3339String(jsDate){
return dojo.date.locale.format(jsDate,{selector: 'date', datePattern:'yyyy-MM-dd\'T\'hh:mm:ssZ'});
}
You can do this generically without Java 7. I have asked 2 questions in StackOverflow on this, within 2012, so there is a solution that does not need any third party libraries.
Just check the implementation presented in the description of my latest question, which also points to the earlier one that discusses exactly this issue.
Related
I tried searching across the web, but unable to find a suitable answer and hence posting here.
I am calling another API which gives me the date-time like
"2022-02-05T17:13:20-06:00[America/Chicago]"
I would like to convert this to a format like
"2022-02-05T17:13:20.000Z" (I am unsure what the milli-second will turn out as)
Could someone help me achieve this?
I am unable to get any example for this specific conversion scenario!!!
Regards,
Sriram
For the sample values given getting to a UTC timestamp should be something like
ZonedDateTime.parse("2022-02-05T17:13:20-06:00[America/Chicago]").toInstant().toString()
The datetime value including the timezone is the canonical representation of a ZonedDateTime and therefore can be parsed as such.
Instant is a UTC timestamp that prints in the form of 2022-02-05T23:13:20Z
You could take more influence on the behavior using a DateTimeFormatter - but since both input and output seem to be standard formats it does not seem necessary.
Here below is a code snippet that I was able to generate....
But, I am unsure of that is correct. Please let me know if you feel anything is incorrect.
String requestTime = "2022-02-05T17:13:20-06:00[America/Chicago]";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX'['VV']'");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(requestTime, formatter);
zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));
I could not find an alternative toDateTimeAtStartOfTheDay. For example
DateTime.now().toLocalDate().toDateTimeAtStartOfDay().plusHours(10)
how would I write above code in Java 8's DateTime library?
Closest I came to ZonedDateTime.now().toLocalDate().atStartOfDay() which just prints 2015-07-21T00:00.
I want something like 2015-07-21T00:00:00.000-04:00
If you need the time as a formatted String and you always like to get 10 o'clock of today, then don't bother calculating that time manually and write it into a format pattern:
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T10:00:00.000'XXX");
The meaning of each letter can be found here: JavaDoc of DateTimeFormatter. 'T10:00:00.000' is a fixed string and won't be parsed, just "added" to the returned String.
You can get the formatted time like this:
ZonedDateTime.now().format(format);
The output would be:
2015-07-21T10:00:00.000-04:00
You can use:
LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault());
I want to define a pattern for the Java SimpleDaterFormat to parse existing strings.
The existing dates look like this: 2011-05-02T13:40:00+02:00.
I tried with different patterns, but I got ParseExceptions. The problem seems to be the timezone format.
Printing the pattern in Java:
yyyy-MM-dd'T'HH:mm:ssZ
2012-03-14T15:40:44+0100
yyyy-MM-dd'T'HH:mm:ssz
2012-03-14T15:41:58MEZ
But how can I get
???
2011-05-02T13:40:00+02:00
I'm using Java 6, not Java 7.
If you can use Java 7 or newer, you can use the XXX pattern to get the timezone to look like +02:00:
yyyy-MM-dd'T'HH:mm:ssXXX
Otherwise you might have to manipulate the date string to remove the colon from the timezone before parsing it.
I know it's a bit old question, but someone else might benefit from my hint.
You can use JodaTime. As library documentation stands:
Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with
a colon, 'ZZZ' or more outputs the zone id.
You can use it as well with java 6. You have more examples in this question
Can somebody please explain to me how I can convert
2009-10-27 14:36:59.580250
into
27.10.2009, 14:36 ?
The first date is available as a string and the second one should be a string as well ;) Up to now I'm not so into date conversion within Java...
Thanks in advance!
You can use java.text.SimpleDateFormat for this. First step is to parse the first string into a java.util.Date object using SimpleDateFormat based on the pattern of the first string. Next step is to format the obtained java.util.Date object into a string based on the pattern of the second string. For example:
String datestring1 = "2009-10-27 14:36:59.580250";
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
System.out.println(datestring2);
Edit: I've removed the .SSSSSS part from the first pattern because it failed. But in my opinion it should in theory have worked with "yyyy-MM-dd HH:mm:ss.SSS" and "yyyy-MM-dd HH:mm:ss.SSSSSS" as well, but it is calculating them as seconds! I consider this as a buggy implementation in SimpleDateFormat. The JodaTime handles the millis/micros perfectly with those patterns.
You can use SimpleDateFormat. Although there's no format specification for micro-seconds (the last fragment of your input), you can make use of the fact that the parser ignores the rest of the string if it has already managed to match the configured pattern:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
System.out.println(formatter.format(parser.parse("2009-10-27 14:36:59.580250")));
The parser will in this case simply ignore the last part ":59.580250" of the input string.
Check out SimpleDateFormat. You can use this to both parse and format. I would suggest parsing the above into a Date object using one SimpleDateFormat, and then formatting to a String using a 2nd SimpleDateFormat.
Note that SimpleDateFormat suffers from threading issues, and so if you're using this in a threaded environment, either create new SimpleDateFormats rather than used static versions, or use the corresponding but thread-safe classes in Joda.
Keep in mind when you do this that you are losing precision. Depending on your specific application, this may or may not matter.
If you already have the original date saved somewhere, this is not an issue. However, if the source date is from a transient source (e.g., streaming in from a physical sensor of some sort), it may be a good idea to persist the interim Date object (output of SimpleDateFormat#parse(String)) somewhere.
Just thought I'd point that out.
Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?
The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.
The javadoc header for SimpleDateFormat is a good source of detailed information. There is also a Java Tutorial with example usages.
The DateFormat class or SimpleDateFormat should get you there. For example, http://www.epochconverter.com/ lists the following example to convert a epoch time to human readable timestamp with Java:
String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
Date instances are insufficient for some purposes.
Use Joda Time instead.
Joda time integrates with Hibernate and other databases.
One gotcha to be aware of is that SimpleDateFormat is NOT thread-safe. Do not put it in a static field and use it from multiple threads concurrently.