Home > front end >  Joda-Time Library Specifying mili second precision
Joda-Time Library Specifying mili second precision

Time:09-17

I am converting the date and time string to Joda DateTime object, using this snipped of the code -

String time = "124204";
String date = "05/09/25";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/mm/yyhhmmss").withZone(DateTimeZone.UTC);
String dateInString = date.concat(time);
DateTime dateTime = DateTime.parse(dateInString, formatter);
System.out.println(dateTime);

I am getting the ouput as - 2025-01-05T00:42:04.000Z

But I want it as - 2025-01-05T00:42:04.000000Z

I want the mili second precision to be 6 digits.

How can I do it? Thanks for the help.

CodePudding user response:

You are confused.

You seem to think you have a string. You don't; you have an object of type DateTime. What you are seeing is the result of invoking toString() on one of these objects, and, like all toString() methods, this is just a debugging aid. It's for your developers' eyeballs and absolutely nothing else (and if you're using it for something else, stop doing that).

If you want the output in some specific format, then make a second DateTimeFormat object and use that. You're using your first to turn strings into datetime objects (the parse method). These formatter objects go both ways; they can also turn datetime objects back into strings, using the format method. Do that. Make the pattern you want, call .format on it handing it the dateTime object you have.

NB: Why are you using jodatime? It is obsoleted by the java.time package, which is written by the same author as jodatime.

CodePudding user response:

As long as you are on at least Java 8, use java.time:

    String time = "124204";
    String date = "05/09/25";
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/yyHHmmss").withZone(ZoneId.of("UTC"));
    String dateInString = date.concat(time);
    ZonedDateTime dateTime = ZonedDateTime.parse(dateInString, parser);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
    System.out.println(dateTime.format(formatter));

This will print 2025-09-05T12:42:04.000000Z. Not sure if you really meant to use the 12-hour format in your input, and I have no experience with it, so I have ignored that.

  • Related