use*_*643 14 java time epoch simpledateformat
在Java中,如何以秒和纳秒的形式打印出自上述时间以来的时间,格式如下:
java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Run Code Online (Sandbox Code Playgroud)
我的意见是:
long mnSeconds;
long mnNanoseconds;
Run Code Online (Sandbox Code Playgroud)
其中两者的总和是自纪元以来经过的时间1970-01-01 00:00:00.0.
Pro*_*eur 18
使用它并除以1000
long epoch = System.currentTimeMillis();
System.out.println("Epoch : " + (epoch / 1000));
Run Code Online (Sandbox Code Playgroud)
你可以这样做
public static String format(long mnSeconds, long mnNanoseconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.");
return sdf.format(new Date(mnSeconds*1000))
+ String.format("%09d", mnNanoseconds);
}
Run Code Online (Sandbox Code Playgroud)
例如
2012-08-08 19:52:21.123456789
Run Code Online (Sandbox Code Playgroud)
如果你真的不需要超过毫秒,你可以做
public static String format(long mnSeconds, long mnNanoseconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return sdf.format(new Date(mnSeconds*1000 + mnNanoseconds/1000000));
}
Run Code Online (Sandbox Code Playgroud)
Instant // Represent a moment in UTC.
.ofEpochSecond( mnSeconds ) // Determine a moment from a count of whole seconds since the Unix epoch of the first moment of 1970 in UTC (1970-01-01T00:00Z).
.plusNanos( mnNanoseconds ) // Add on a fractional second as a count of nanoseconds. Returns another `Instant` object, per Immutable Objects pattern.
.toString() // Generate text representing this `Instant` object in standard ISO 8601 format.
.replace( "T" , " " ) // Replace the `T` in the middle with a SPACE.
.replace "Z" , "" ) // Remove the `Z` on the end (indicating UTC).
Run Code Online (Sandbox Code Playgroud)
该java.time框架是建立在Java 8和更高版本.这些类取代旧的麻烦日期时间类,如java.util.Date,.Calendar,java.text.SimpleDateFormat,java.sql.Date,等等.该乔达时球队还建议迁移java.time.
Instant本Instant类表示UTC时间线,分辨率高达纳秒了一下.
long mnSeconds = … ;
long mnNanoseconds = … ;
Instant instant = Instant.ofEpochSecond( mnSeconds ).plusNanos( mnNanoseconds );
Run Code Online (Sandbox Code Playgroud)
要获取表示此日期时间值的String,请调用of.
Instant instant = Instant.ofEpochSecond( mnSeconds , mnNanoseconds );
Run Code Online (Sandbox Code Playgroud)
您将获得一个Instant::toString标准ISO 8601格式的值.2011-12-03T10:15:30.987654321Z如果您愿意,请用空格替换.对于其他格式,请搜索Stack Overflow以了解T.
该java.time框架是建立在Java 8和更高版本.这些类取代麻烦的老传统日期时间类,如DateTimeFormatter,java.util.Date,和Calendar.
现在处于维护模式的Joda-Time项目建议迁移到java.time类.
要了解更多信息,请参阅Oracle教程.并搜索Stack Overflow以获取许多示例和解释.规范是JSR 310.
您可以直接与数据库交换java.time对象.使用符合JDBC 4.2或更高版本的JDBC驱动程序.不需要字符串,不需要课程.SimpleDateFormat
从哪里获取java.time类?
该ThreeTen-额外项目与其他类扩展java.time.该项目是未来可能添加到java.time的试验场.您可以在此比如找到一些有用的类java.sql.*,Interval,YearWeek,和更多.
| 归档时间: |
|
| 查看次数: |
46372 次 |
| 最近记录: |