Java 从日期中提取日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2619691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
extract day from Date
提问by Daniel
I receive a timestamp from a SOAPservice in milliseconds. So I do this:
我从SOAP服务收到一个以毫秒为单位的时间戳。所以我这样做:
Date date = new Date( mar.getEventDate() );
How can I extract the day of the month from date, since methods such as Date::getDay()
are deprecated?
由于Date::getDay()
不推荐使用诸如此类的方法,我如何从日期中提取月份中的哪一天?
I am using a small hack, but I do not think this is the proper way to obtain day-of-month.
我正在使用一个小技巧,但我认为这不是获取月份的正确方法。
SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );
回答by cletus
回答by Ortomala Lokni
Given the Date constructorused in the question
鉴于问题中使用的日期构造函数
Date date = new Date(mar.getEventDate());
The method mar.getEventDate()
returns a long
that represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
该方法mar.getEventDate()
返回一个long
表示自称为“纪元”的标准基准时间(即格林威治标准时间 1970 年 1 月 1 日 00:00:00)以来的指定毫秒数。
Java 8 and later
Java 8 及更高版本
In Java 8, you can extract the day of the month from this value, assuming UTC, with
在 Java 8 中,假设 UTC,您可以从此值中提取月份中的第几天,
LocalDateTime.ofEpochSecond(mar.getEventDate(),0,ZoneOffset.UTC).getDayOfMonth();
Note also that the answer given by cletus assume that mar.getEventDate()
returns a Date
object which is not the case in the question.
另请注意,cletus 给出的答案假定mar.getEventDate()
返回的Date
对象与问题中的情况不同。
回答by Basil Bourque
Update:The Joda-Timeproject is now in maintenance mode, with the team advising migration to the java.timeclasses. See Tutorial by Oracle.
更新:该乔达时间的项目现在处于维护模式,与团队的建议迁移java.time类。请参阅Oracle 教程。
See the correct Answerby Ortomala Lokni, using the modern java.timeclasses. I am leaving this outmoded Answer intact as history.
请参阅Ortomala Lokni 使用现代java.time类编写的正确答案。我将这个过时的答案作为历史原封不动地保留下来。
The Answerby Lokni is correct.
Lokni的回答是正确的。
Here is the same idea but using Joda-Time2.8.
这是相同的想法,但使用Joda-Time2.8。
long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;