2

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

Community
  • 1
  • 1
HMdeveloper
  • 2,772
  • 9
  • 45
  • 74
  • 1
    The date returned by MongoDB is an `ISODate`, please see the linked question: http://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date – BatScream Jan 06 '15 at 19:53

3 Answers3

7

You can use this method to parse the mongo date format. But in here we are neglecting time zone. So use this if the time zone doesn't matter.

private static String convertMongoDate(String val){
    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat outputFormat= new SimpleDateFormat("yyyy/MM/dd");
    try {
        String finalStr = outputFormat.format(inputFormat.parse(val));
        System.out.println(finalStr);
        return finalStr;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "";
}
thilina Kj
  • 1,300
  • 13
  • 25
6

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

wassgren
  • 18,651
  • 6
  • 63
  • 77
  • when I use this line final LocalDateTime parsed = LocalDateTime.parse(result.get("_id").toString() , inputFormat);i get the following error: Text 'Sun Oct 19 01:00:00 ADT 2014' could not be parsed at index 0 – HMdeveloper Jan 06 '15 at 17:37
  • it seems the json returns the date in the following format :Sun Oct 19 01:00:00 ADT 2014 – HMdeveloper Jan 06 '15 at 17:37
  • Ok, then you can use the following pattern for the inputFormatter: `EEE MMM dd HH:mm:ss zzz yyyy`. I was under the impression (from the file you provided) that the input date looked like this: `2014-10-21T04:00:00.000Z`. – wassgren Jan 06 '15 at 17:45
  • Are u sure that one will work with this Sun Oct 19 01:00:00 ADT 2014, because I get the same error! – HMdeveloper Jan 06 '15 at 18:01
  • Can you post the stacktrace? – wassgren Jan 06 '15 at 18:02
  • Do you mean this:Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sun Oct 19 01:00:00 ADT 2014' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849) at java.time.LocalDateTime.parse(LocalDateTime.java:492) – HMdeveloper Jan 06 '15 at 18:09
  • Even if I do not use json and use this instead I will get the same error:final LocalDateTime parsed = LocalDateTime.parse("Sun Oct 19 01:00:00 ADT 2014" , inputFormat); – HMdeveloper Jan 06 '15 at 18:11
  • Then I get this error Exception in thread "main" java.time.DateTimeException: Unable to extract value: class java.time.LocalDateTime at this line:System.out.println(outputFormat1.format(parsed)); – HMdeveloper Jan 06 '15 at 18:18
  • 1
    Why are you using `LocalDateTime` when the date includes a time zone? Wouldn't `ZonedDateTime` be a better choice? – David Conrad Jan 06 '15 at 20:18
  • The answer is here thankd a lot all for helping :http://stackoverflow.com/questions/27805732/converting-date-from-one-format-to-another-does-not-work – HMdeveloper Jan 06 '15 at 20:21
  • min API level 26 – DragonFire May 23 '20 at 06:07
0

I would suggest you to do something like below.

SimpleDateFormat original = new SimpleDateFormat("yyyy-MM-ddThh:mm:sssZ");
SimpleDateFormat output= new SimpleDateFormat("yyyy/MM/dd");
String isoFormat = original.format(result.get("_id"));
Date d = original.parse(isoFormat);
String formattedTime = output.format(d);

System.out.println(formattedTime);
dReAmEr
  • 6,986
  • 7
  • 36
  • 63
  • The problem is that the date returns from json is as follow :Sun Oct 19 01:00:00 ADT 2014 and exactly at this line I will stuck : Date d = original.parse(result.get("_id")); – HMdeveloper Jan 06 '15 at 17:41
  • i have updated my answer,which should handle this case can you test this? – dReAmEr Jan 06 '15 at 17:44
  • 1
    Not working I get this error :Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'T' – HMdeveloper Jan 06 '15 at 18:06
  • 1
    @HamedMinaee: You could use new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:sss") instead. – mam10eks Apr 10 '17 at 16:06