[英]Convert UTC date from scientific notation to Java.util.Date
I'm trying to convert the created_utc
date from Reddit's json to a Date
object, but I keep getting an "Unparceable" error. 我正在尝试将
created_utc
日期从Reddit的json转换为Date
对象,但我不断收到“Unparceable”错误。 An example of their dates is: created_utc": 1.43701862E9,
which I'm told is a unix timestamp. 他们的日期的一个例子是:
created_utc": 1.43701862E9,
我被告知是一个unix时间戳。
From my research this code should convert it: 根据我的研究,这段代码应该转换它:
String date = "1.43701862E9";
java.util.Date time = new java.util.Date((long)date*1000);
but obviously I'm getting an error on multiplying the date by 1000. 但显然我在将日期乘以1000时遇到错误。
This is the code I normally use to convert string dates: 这是我通常用来转换字符串日期的代码:
String date = "1.43701862E9";
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.parse(date);
This should work for you: 这应该适合你:
public static void main(String[] args) {
String date = "1.43701862E9";
java.util.Date time = new java.util.Date(Double.valueOf(date).longValue()*1000);
System.out.println(time);
}
Output: 输出:
Wed Jul 15 23:50:20 EDT 2015
Since you're using scientific notation you can't parse the String
using the Long
class: Long.parseLong(String s)
(Nor can you simply cast a String, as you're trying). 由于您使用的是科学记数法,因此无法使用
Long
类解析String
: Long.parseLong(String s)
(在您尝试时,也不能简单地转换字符串)。 Instead, I used the Double.valueOf()
method and preserve the Long
using .longValue()
相反,我使用
Double.valueOf()
方法并使用.longValue()
保留Long
The answer by Trobbins is correct but old-school. Trobbins 的答案是正确的,但老派。 I lifted that Answer's math, and used the new java.time classes.
我解除了Answer的数学,并使用了新的java.time类。
In Java 8 and later, you can use the new java.time package which supplants the troublesome old java.util.Date /.Calendar classes. 在Java 8及更高版本中,您可以使用新的java.time包 ,它取代了麻烦的旧java.util.Date /.Calendar类。 ( Tutorial )
( 教程 )
String input = "1.43701862E9";
long milliSinceEpoch = Double.valueOf( input ).longValue() * 1_000L ;
Instant instant = Instant.ofEpochMilli( milliSinceEpoch ) ;
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ) ;
Try to avoid java.util.Date/.Calendar, but if need be you can convert. 尽量避免使用java.util.Date/.Calendar,但如果需要,可以转换。
java.util.Date date = Date.from( zdt.toInstant() ); // Or… Date.from( instant );
java.util.Calendar calendar = GregorianCalendar.from( zdt );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.