看起来问题和接受的答案都忽略了时区,这可能是一个问题。
使用Joda-Time或 Java 8 中的新 java.time.* 包,这项工作要容易得多。你说你有long
原始价值,所以让我们从那里开始,假设它代表 Unix 纪元(1970)的毫秒数。根本不需要处理创建或解析日期的字符串表示。Joda-Time 提供了许多访问年、月等数字和名称的点。Joda-Time 将名称本地化为瑞典语或英语。
日期样式代码是一对字符。第一个字符是日期样式,第二个字符是时间样式。指定字符“S”表示短样式,“M”表示中号,“L”表示长,“F”表示完整。通过指定样式字符“-”可以省略日期或时间。
long input = DateTime.now().getMillis();
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Stockholm" );
DateTime dateTime = new DateTime( input, timeZone );
int year = dateTime.getYear();
int month = dateTime.getMonthOfYear(); // 1-based counting, 1 = January. Unlike crazy java.util.Date/Calendar.
int dayOfMonth = dateTime.getDayOfMonth();
int hourOfDay = dateTime.getHourOfDay();
int minuteOfHour = dateTime.getMinuteOfHour();
java.util.Locale localeSweden = new Locale( "sv", "SE" ); // ( language code, country code );
String monthName_Swedish = dateTime.monthOfYear().getAsText( localeSweden );
String monthName_UnitedStates = dateTime.monthOfYear().getAsText( java.util.Locale.US );
DateTimeFormatter formatter_Sweden = DateTimeFormat.forStyle( "LM" ).withLocale( localeSweden ).withZone( timeZone );
DateTimeFormatter formatter_UnitedStates_NewYork = DateTimeFormat.forStyle( "LM" ).withLocale( java.util.Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String text_Swedish = formatter_Sweden.print( dateTime );
String text_UnitedStates_NewYork = formatter_UnitedStates_NewYork.print( dateTime );
DateTime dateTimeUtcGmt = dateTime.withZone( DateTimeZone.UTC );
转储到控制台...</p>
System.out.println( "dateTime: " + dateTime );
System.out.println( "monthName_Swedish: " + monthName_Swedish );
System.out.println( "monthName_UnitedStates: " + monthName_UnitedStates );
System.out.println( "text_Swedish: " + text_Swedish );
System.out.println( "text_UnitedStates_NewYork: " + text_UnitedStates_NewYork );
System.out.println( "dateTimeUtcGmt: " + dateTimeUtcGmt );
运行时……</p>
dateTime: 2014-02-16T07:12:19.301+01:00
monthName_Swedish: februari
monthName_UnitedStates: February
text_Swedish: den 16 februari 2014 07:12:19
text_UnitedStates_NewYork: February 16, 2014 1:12:19 AM
dateTimeUtcGmt: 2014-02-16T06:12:19.301Z