从日期中提取日期

2022-09-02 09:17:57

我从 SOAP 服务收到一个时间戳(以毫秒为单位)。所以我这样做:

Date date = new Date( mar.getEventDate() );

如何从日期中提取月份中的某一天,因为诸如Date::getDay()之类的方法已被弃用?

我正在使用一个小黑客,但我不认为这是获取月中某一天的正确方法。

SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );

答案 1

为此使用“日历”

Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);

答案 2

更新:Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。请参阅 Oracle 的教程

请参阅Ortomala Lokni使用现代java.time的正确答案。我把这个过时的答案原封不动地当作历史。


Lokni的答案是正确的。

这是同样的想法,但使用Joda-Time 2.8。

long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;  // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;