Frage

In, Java how to use Joda-Time to get date and time using time zone. The server is running UTC +0300. But I need to use UTC +0530 i.e. Indian standard time. I need to use like this

DateTimeZone zone = DateTimeZone.forID("Asia/Calcutta");

But how to get date and time in this format : dd-MM-yyyy hh:mm:ss

Any help is greatly appreciated.

War es hilfreich?

Lösung

You need a DateTimeFormatter:

private static final DateTimeFormatter FORMATTER
    = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss");

Then you can .print() your DateTime:

// Returns a String
FORMATTER.print(new DateTime(zone));

Andere Tipps

The other answers were partial. Here's a bit more info.

To adjust for time zone, you can either:

  • Create a new DateTime instance with a different time zone assigned.
  • Have the formatter apply a time zone during the creation of the string representation of the date-time.
DateTime dateTimeMoscow = new DateTime( DateTimeZone.forID( "Europe/Moscow" ) );
DateTime dateTimeIndia = dateTimeMoscow.withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss").withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
String output = formatter.print( dateTimeMoscow ); // Formatter adjusts zone from Moscow to Kolkata.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top