Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate DateTime to Date and Time with time zone `Z` at the end, in Joda-Time

I have a Joda-Time DateTime object and need to have date and time separately, with time zone label at the end:

DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("YYYY-MM-ddZ"));
System.out.println(dateTime.toString("HH:mm:ssZ"));

In this case the output will be:

2014-02-27+0000
15:10:36+0000

Almost exactly what I need, but it is possible to have it like this?

2014-02-27Z
15:10:36Z
like image 456
XpressOneUp Avatar asked Dec 27 '25 20:12

XpressOneUp


2 Answers

Here's a working example

DateTime dateTime = new DateTime();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd")
            .appendTimeZoneOffset("Z", false, 2, 2)
            .toFormatter();
System.out.println(formatter.print(dateTime.withZone(DateTimeZone
            .forID("Zulu"))));

Basically, if the time zone offset is zero, you print Z. Since Zulu or UTC has an offset of 0, that's what will be printed.

like image 174
Sotirios Delimanolis Avatar answered Dec 30 '25 11:12

Sotirios Delimanolis


If you're trying to use Military codes (i.e. Z for GMT see: http://www.timeanddate.com/library/abbreviations/timezones/military/z.html) you could so something like this:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import java.util.Date;

public class CalendarExample {

  static final String MILITARY_OFFSETS = "YXWVUTSRQPONZABCDEFGHIKLM";
  static final int MILLIS_IN_HOUR = 1000*60*60;

  public static void main(String[] args) {
    System.out.println(formatDate(new Date(), "yyyy-MM-dd", "GMT")); // 2014-02-27Z
    System.out.println(formatDate(new Date(), "HH:mm:ss", "GMT"));
    System.out.println(formatDate(new Date(), "yyyy-MM-dd", "EST"));
    System.out.println(formatDate(new Date(), "HH:mm:ss", "EST"));
  }

  static String formatDate(Date date, String dateTimeFormat, String timezoneCode) {
    Calendar calendar = new GregorianCalendar();
    TimeZone tz = TimeZone.getTimeZone(timezoneCode);
    calendar.setTimeZone(tz);
    int offset = calendar.get(Calendar.ZONE_OFFSET)/MILLIS_IN_HOUR;

    // System.out.println(timezoneCode + " Offset is " + offset + " hours");
    String timeZoneCode = MILITARY_OFFSETS.substring(offset + 12, offset + 13);
    SimpleDateFormat dateFmt = new SimpleDateFormat(dateTimeFormat + "'" + timeZoneCode + "'");

    return dateFmt.format(date);
  }

}

output:

2014-02-27Z
11:57:44Z
2014-02-27R
11:57:44R
like image 39
rainkinz Avatar answered Dec 30 '25 12:12

rainkinz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!