Java SimpleDateFormat similar to C#

天大地大妈咪最大 提交于 2019-12-11 10:43:53

问题


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 this method:

public static Date getTodayDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ:Z");
    Date date = new Date();
    String dateString = dateFormat.format(date);
    Date today = parseFromNormalStringToDate(dateString);
    return today;
}

but I get this return

2013-09-16T11:47:55.235+0200:+0200;

thanks for the help!


回答1:


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

SimpleDateFormat dateFormat = new SimpleDateFormat("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.
Date date = new Date();
String dateString = 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:-

public static void main(String[] args) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");
    Date date = new Date();
    String dateString = dateFormat.format(date); // You need to use "dateString" for your JSON
    System.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:-

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

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



回答2:


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

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


来源:https://stackoverflow.com/questions/18825131/java-simpledateformat-similar-to-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!