-1

I am using JodaTime to create ISO 8601 String.

DateTime jodatime = new DateTime(2016, 04, 05, 23, 59, 59, 999, DateTimeZone.UTC);
String converted = jodatime.toDateTimeISO().toString();

Right now, I am getting the following:

2016-04-06T06:59:59.999Z

However, I want to truncate/remove seconds and milliseconds.

2016-04-05T23:59Z

Does anyone know how to do this with the least hacky way? And can anyone tell me if that shortened version of ISO8601 can be recognized by date parsing libraries?

Ryan
  • 130
  • 11

2 Answers2

3

The normal way of formatting a Joda Time value is using a formatter. In this case, the format you want is already available, except for the Z:

DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinute();
String text = formatter.print(value);

The Z is slightly tricky - I don't believe you can specify exactly what you want with a simple pattern (DateTimeFormat.forPattern) but you can use a DateTimeFormatterBuilder:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendYear(4, 9)
    .appendLiteral('-')
    .appendMonthOfYear(2)
    .appendLiteral('-')
    .appendDayOfMonth(2)
    .appendLiteral('T')
    .appendHourOfDay(2)
    .appendLiteral(':')
    .appendMinuteOfHour(2)
    .appendTimeZoneOffset("Z", true, 2, 4)
    .toFormatter()
    .withLocale(Locale.US);

I believe that does exactly what you want.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I used ` ISODateTimeFormatter.dateHourMinue().withZone(DateTimeZone.UTC)` but it is not showing 'Z' nor '+00:00" – Ryan Apr 05 '16 at 21:38
  • Sorry, hadn't spotted the Z. If it's always UTC, you could just the `Z` at the end with string concatenation. Otherwise, build a new `DateTimeFormatter` - will edit to show that. – Jon Skeet Apr 05 '16 at 21:39
  • @Ryan: Sorry, laptop has just died... Will your values always be UTC? Would +00:00 be acceptable instead of Z? Will update answer when laptop is back up... – Jon Skeet Apr 05 '16 at 21:45
  • Z is preferred to +00:00.. But latter is also acceptable. I am looking for something like `dateTimeNoMillis()` but also need to exclude second.. – Ryan Apr 05 '16 at 21:56
  • thank you very much. Initially, I wanted built-in method such as `dateTimeNoMillis()` so that I do not need to build format myself. But I cannot find one. I guess everyone is satisfied with precision to seconds. Builder is working very nice though, thank you again. – Ryan Apr 05 '16 at 22:25
  • Thanks for your tip, just for who is trying this, the class name now is "ISODateTimeFormat" instead of "ISODateTimeFormatter". joda-time version 2.9.9 – luizMello Aug 31 '17 at 13:23
  • @luizMello: Just a typo - I'd linked to the right code. Will edit. – Jon Skeet Aug 31 '17 at 13:24
0

You can remove seconds and milliseconds of a joda DateTime instance like this easily.

DateTime now = DateTime.now();
DatiTime nowUpToMinuts = now.withMillisOfSecond(0).withSecondOfMinute(0);
Chanaka Fernando
  • 2,176
  • 19
  • 19