问题
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.
回答1:
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));
回答2:
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.
来源:https://stackoverflow.com/questions/21952989/java-joda-time-get-date-time