我想把长格式的milliSeconds转换成公历。通过在网上搜索,我使用以下代码:
public static String getStringDate(int julianDate){
GregorianCalendar gCal = new GregorianCalendar();
Time gTime = new Time();
gTime.setJulianDay(julianDate);
gCal.setTimeInMillis(gTime.toMillis(false));
String gString = Utils.getdf().format(gCal.getTime());
return gString;
}
public static SimpleDateFormat getdf(){
return new SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US);
}是的,代码有效,但我发现只有日期和时间是正确的,但分钟上有错误。如果事情发生在2014-11-06,14:00,它会给我2014-11-06,14:11。我想知道有什么解决办法来修改它,或者不建议把时间转换成公历。非常感谢!
发布于 2014-11-12 05:04:50
这个问题实际上很简单,修改SimpleDateFormat(“yyyy,HH:MM",Locale.US)
SimpleDateFormat(“yyyy,HH:mm",Locale.getDefault());
会解决这个问题
发布于 2018-02-01 05:26:01
tl;dr
Instant.ofEpochMilli( millis ) // Convert count-from-epoch into a `Instant` object for a moment in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Adjust from UTC to a particular time zone. Same moment, different wall-clock time. Renders a `ZonedDateTime` object.
.format( // Generate a String in a particular format to represent the value of our `ZonedDateTime` object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" )
)java.time
现代方法使用java.time类而不是那些麻烦的遗留类。
将自1970年第一时刻(1970-01-01T00:00Z)的划时代引用以来的毫秒数转换为Instant对象。请注意,Instant能够提供更细的纳秒粒度。
Instant instant = Instant.ofEpochMilli( millis ) ;那一刻发生在UTC。若要调整到另一个时区,请应用ZoneId获取ZonedDateTime。
时区是确定日期的关键。在任何特定时刻,全球各地的日期因地区而异。例如,午夜后几分钟在法国巴黎是一个新的一天,而仍然“昨天”在魁北克省。
如果没有指定时区,JVM将隐式应用其当前默认时区。默认情况在任何时候都可能发生变化,因此您的结果可能会有所不同。最好将所需/预期的时区显式地指定为参数。
以continent/region格式指定continent/region,如America/Montreal、Africa/Casablanca或Pacific/Auckland。不要使用3-4字母的缩写,如EST或IST,因为它们不是真正的时区,不标准化,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;使用DateTimeFormatter对象生成所需格式的字符串。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" , Locale.US ) ;
String output = zdt.format( f ) ;关于java.time
http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html框架内置到Java8和更高版本中。这些类取代了麻烦的旧遗赠日期时间类,如java.util.Date、Calendar和SimpleDateFormat。
http://www.joda.org/joda-time/项目现在在维护模式中,建议迁移到java.time类。
要了解更多信息,请参见http://docs.oracle.com/javase/tutorial/datetime/TOC.html。并搜索堆栈溢出以获得许多示例和解释。规范是JSR 310。
在哪里获得java.time类?
https://stackoverflow.com/questions/26794586
复制相似问题