Skip to content Skip to sidebar Skip to footer

Java Simpledateformat Similar To C#

I have to get a today Date with this format {'Date':'2013-09-11T14:47:57.8895887+02:00'}. This is because my Json Service is studied for Windows Phone and C# code. I tried with thi

Solution 1:

There are 2 things to be changed here. First the format.

SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX"); // This should work for you. Though I must say 6 "S" is not done. You won't get milliseconds for 6 precisions.Datedate=newDate();
StringdateString= dateFormat.format(date); // You need to use "dateString" for your JSON

And the second thing, the formatted date is the which you need to put in your JSON and not parse it back to Date. But Date doesn't have a formatting option. You can only get a String representation of the Date in the format you need using SDF.

Ex:-

publicstaticvoidmain(String[] args) {
    SimpleDateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");
    Date date = newDate();
    String dateString = dateFormat.format(date); // You need to use "dateString" for your JSONSystem.out.println(dateString); // Output
}

and the output for this is

2013-09-16T15:39:16.000257+05:30

6 digit precision in milliseconds is not possible. If you see the docs of SDF in Java 7, you can find this:-

enter image description here

The highlighted example is the one you need, but with 6 milliseconds precision, which is not possible. Thus, you can use 6 S but it will just add 3 leading zeroes before the actual 3 millisecond digits! This is the only workaround possible in your case!

Edit:-

The SimpleDateFormat of Android does not contain X. It provides Z instead. Therefore your new format string will be

yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ

SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"); // For Android

Solution 2:

The problem is with the "Z:Z" Try "X" this instead :

publicstaticDategetTodayDate() {
    SimpleDateFormat dateFormat = newSimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSX");
    Date date = newDate();
    String dateString = dateFormat.format(date);
    Date today = parseFromNormalStringToDate(dateString);
    return today;
}

Post a Comment for "Java Simpledateformat Similar To C#"