Search code examples
javamongodb-querymongodb-java

Converting the date returned from mongo to this format 2015-10-25


I have a json file returned from mongo db as follow:

[
{
    "_id": {
        "$date": "2014-10-19T04:00:00.000Z"
    },
    "value": 29
},
{
    "_id": {
        "$date": "2014-10-20T04:00:00.000Z"
    },
    "value": 20
},
{
    "_id": {
        "$date": "2014-10-21T04:00:00.000Z"
    },
    "value": 21
}
]

Now I want to read the date in java in the following format: 2014/10/25

but when I use:

System.out.println("DAte is : "+result.get("_id").toString() );

the result is :

DAte is : Sun Oct 19 01:00:00 ADT 2014

Then only thing that comes to my mind is to use substring and manually convert the date to 2014-10-25 but I am sure there would better way. Does any one have any idea?

Update :

Here is the answer :

converting date from one format to another does not work

thanks a lot for helping


Solution

  • Why don't you use the DateTimeFormatter? Then you can parse your dates this way:

    // The test string
    String str = "Sun Oct 19 01:00:00 ADT 2014";
    
    // Formatter for the input date
    final DateTimeFormatter inputFormat = 
            DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
    
    // The parsed date
    final ZonedDateTime parsed = ZonedDateTime.parse(str, inputFormat);
    
    // The output format(s). Specify the one you need
    final DateTimeFormatter outputFormat1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    final DateTimeFormatter outputFormat2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    // Print
    System.out.println(outputFormat1.format(parsed)); // -> 2014/10/19
    System.out.println(outputFormat2.format(parsed)); // -> 2014-10-19
    

    This article provides some good reading for how to parse and format dates. The class DateTimeFormatter is available for Java 8, if you are using older versions of Java the class SimpleDateFormat may be used instead (it uses a similar strategy for handling dates but is unfortunately not thread-safe).

    Edit: Updated the formatter after input from the OP