convert timestamp to ISO860 in java, [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting ISO8601-compliant String to java.util.Date
I have issues when changing the timestamp to ISO 8601 in JS as it errors at 'topicDate' in IE and Firefox, but it works in Chrome. So i want to change the timestamp to ISO 8601 in the server side and send that via json instead. Can anyone help me how to convert the below time stamp to ISO 8601 format in Java using standard classes? Any other suggesting about this approach is also welcomed.
Time sent via json
"topic_lstUpdate" : "2012-09-07 19:39:56.439",
JS script
var topicDate = new Date(args.topic_lstUpdate);
var topicDateISO = topicDate.toISOString();
var topicDateTimeago=jQuery.timeago(topicDate);

To format within Java on the server-side:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String my8601formattedDate = df.format(new Date());
It is recommended that you include the T delimiter - but if you're certain your requirements on both ends permit excluding it, you are permitted to omit it. See http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations for details.

It's almost there already. You can use this JavaScript to convert it:
topicDate.replace(" ", "T");

Related

SimpleDateFormat question for timezone offset +AA:BB

I am currently using the following SimpleDateFormat pattern:
String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss,SSSXXX";
This works fine, however some raspberry Pi java implementations don't recognize it properly:
timestamp 2020-01-21T09:41:45,434Z
In most cases, this won't be an issue, however the offset is buggy for some raspberry PIs; I don't want that. Is there an alternative pattern with the same offset format (+/-HH:mm) that could work? I've tried all kinds of patterns, but none seem to produce the same output.
I also used the following tool to search for such a pattern: https://javadevtools.com/simpledateformat , though it was fruitless.
NOTE: An example output of this format is 1997-07-16T19:20:30,45+01:00 , with a colon in the offset.
If you were using java.time, especially the two classes java.time.OffsetDateTime (pattern symbols are explained in this JavaDoc) and java.time.format.DateTimeFormatter, you or your Raspberry Pi would be able to correctly parse the timestamp (which has a strange format using a comma to separate fractions of second from the seconds).
The following example parses your timestamp and outputs the default format:
public static void main(String[] args) {
String timestamp = "1997-07-16T19:20:30,45+01:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss[,SSS]xxx");
OffsetDateTime odt = OffsetDateTime.parse(timestamp, dtf);
System.out.println(odt);
}
Output:
1997-07-16T19:20:30.450+01:00
I confirm that this is not a Pi issue. I switched my local time zone to UTC and ran the following example:
long current = System.currentTimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss,SSSXXX");
Date date = new Date(current);
String parsed = format.format(date);
System.out.println(parsed);
2020-08-31T15:05:27,872Z
And the Z appeared, on Windows 10. I have missed that part of the ISO spec. It seems I have to workaround my tests for this situation :). Thanks everyone!

Date.plus not working in 2.5.4 Groovy Runtime, what is the alternative?

We want to add days to the current date and format it in a specific way. This was solved in Groovy 2.4.13 and the following date manipulation works fine:
​today = new Date()+90;today.format('yyyy-MM-dd HH:mm:ss.S');
Result: 2019-12-02 08:07:15.294
In Groovy 2.5.4 the same expression throws this exception:
groovy.lang.MissingMethodException: No signature of method:
java.util.Date.plus() is applicable for argument types: (Integer)
values: [90] Possible solutions: parse(java.lang.String),
split(groovy.lang.Closure), use([Ljava.lang.Object;),
is(java.lang.Object), wait(), clone() at
Script1.run(Script1.groovy:3)
I was able to reproduce this behaviour in "Groovy sandboxes" online:
Working fine here: groovy-playground (Version 2.4.1.5)
Failing here: groovyconsole (Version 2.5.7)
What is the working alternative in this case? I have read about a new Date API, but couldn't find the details about how to use it, with date manipulation (+ 90 days for example).
Take a look at TimeCategory
import groovy.time.TimeCategory
def theDate = use(TimeCategory){new Date() + 90.days}.format('yyyy-MM-dd HH:mm:ss.S')
I agree with Ole V.V.'s recommendations to use the new Date/Time API. Here is how you would write his Java sample in a more Groovy style.
// you can assemble aggregate types by left shifting the aggregates
// I'm not endorsing this approach, necessarily, just pointing it out as an alternative
ZonedDateTime now = LocalDate.now() << LocalTime.now() << ZoneId.of('Africa/Bamako')
// the plus operator is overloaded
ZonedDateTime in90Days = now + 90
// you can pass a String to format without needed a full DateTimeFormatter instance
println in90Days.format('uuuu-MM-dd HH:mm:ss.S')
While Groovy adds some further support for the old Java Date class, I still believe that you should not use it. It was always poorly designed and is now long outdated. Instead use java.time, the modern Java date and time API. I am sorry that I will have to trust you to translate from Java code.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.S");
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Africa/Bamako"));
ZonedDateTime in90Days = now.plusDays(90);
System.out.println(in90Days.format(formatter));
Output when running just now was:
2020-01-01 08:37:13.3
Please substitute your desired time zone if it didn’t happen to be Africa/Bamako.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can use Calendar to achieve that
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE, 90);
Date date = cal.getTime();
All steps must be separate and not in a single line.

Format date from standard php format to userdefined style in java

I am receiving the date format string from a server (eg:"j,n,Y", "d,M,yyyyy", "d de M de Y" etc). These are user defined and it varies from user to user.
"j,n,Y" means an output like 1,20,2013
this in java will be "d,M,yyyy"
Does anyone know any solid library to convert date format String in java, which format the String to compatible with SimpleDateFormat?
I mean I will receive "j,n,Y" and after using the function, I need it to be "d,M,yyyy"
for now I'm just using a find and replace
....
dateFormat = dateFormat.replaceAll("d","dd");
.... more replaces
....
but I know that there are lot of posibilities not contemplated, that's why I'm looking for a better option.

Java XML RPC date iso 8601 with timezone

I am having a hard time trying to make a web service client work. It is a XML RPC specification. I am using Apache WS XML-RPC library, which I find full of holes that causes problem due to Serialization. I have to send a Date parameter for the library to add the tags , however the web service expects it with the TZ, that means adding -0500 at the end of the Date object. If I dont send it as Date Object, it wont add the tags and it will fail. And when trying to do this:
DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZ");
String fecha = df.format(new Date());
Date date = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZ").parse(fecha);
And using parameter date, and it always sends it as
<dateTime.iso8601>20130517T20:30:33</dateTime.iso8601>
Can't find a way for it to send it as Date object in the format above but with the -0500 at the end. Any help would be appreciated.

Google Calendars API - setTimeMax causing error

I'm trying to retrieve a list of events from a google calendar, using the Java api (jar version v3-rev9-1.7.0-beta)
This code works fine
Events e = service.events().list("primary").
setMaxResults(3).
execute();
where service is a Calendar object.
However, if I add a setTimeMin or setTimeMax parameter, like this
Date now = new java.util.Date();
Events e = service.events().list("primary").
setTimeMin(new DateTime(now)).
setMaxResults(3).
execute();
it returns a failure message, "Bad Request".
(note that as of this version, the setTime functions take a google DateTime object. I've also tried with the previous version of the jar, which takes a string, but received the same message).
So I was just wondering if anyone has successfully used these functions - perhaps they're not supposed to be called in this manner? Is there a way to get more detail back on the error?
Thanks :)
DateTime startTime = new DateTime(new Date(), TimeZone.getDefault());
Sorts the problem
I also encountered this. It seems the format of the DateTime.toString() or DateTime.toStringRfc3339() methods are incorrect as input to setTimeMin().
The DateTime.toString() format is:
2012-07-04T21:02:16.590
yyyy-MM-dd'T'HH:mm:ss.SSS (SimpleDateFormat notation)
The format which it expects seems to be close to xsd:datetime format (whatever that is):
2012-07-04T21:02:16Z (zulu, gmt)
2012-07-04T21:02:16-07:00 (mst, -7h)
2012-07-04T21:02:16-0700 (it also works without the colon in the timezone)
yyyy-MM-dd'T'HH:mm:ssZ (SimpleDateFormat)
Formatting can be done with a SimpleDateFormat:
SimpleDateFormat FMT_TIME=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String fromTimeStr=FMT_TIME.format(new Date());
Events evts = client.events().list(cal.getUid()).setTimeMin(fromTimeStr)
.execute();
Now, since I'm using the older API, I'm not sure how this would be done if the only method is setTimeMin(DateTime), but this should get you closer.
The Google documentation or source should mention this somewhere.

Categories