如何将UUID格式转换为日期格式2011-04-22?
例如,我有这样的UUID
118ffe80-466b-11e1-b5a5-5732cf729524.如何将此格式转换为日期格式?
我试过了
String uuid="118ffe80-466b-11e1-b5a5-5732cf729524";
UUID uid = UUID.fromString(uuid);
long ls=convertTime(uid.timeStamp()); // it returns long value
public String convertTime(long time){
System.out.println("====="+time);
Date date = new Date(time);
Format format = new SimpleDateFormat("yyyy/MM/dd");
return format.format(date).toString();
}输出:4294744/11/02
同样适用于perl
$uuid='ef802820-46b3-11e2-bf3a-47ef6b3e28e2';
$uuid =~ s/-//g;
my $timelow = hex substr( $uuid, 2 * 0, 2 * 4 );
my $timemid = hex substr( $uuid, 2 * 4, 2 * 2 );
my $version = hex substr( $uuid, 2 * 6, 1 );
my $timehi = hex substr( $uuid, 2 * 6 + 1, 2 * 2 - 1 );
my $time = ( $timehi * ( 2**16 ) + $timemid ) * ( 2**32 ) + $timelow;
my $epoc = int( $time / 10000000 ) - 12219292800;
my $nano = $time - int( $time / 10000000 ) * 10000000;
#$time_date = scalar localtime $epoc;
#print strftime( '%d-%m-%Y %H:%M:%S', localtime($epoc) );
#print "\n Time: ", scalar localtime $epoc, " +", $nano / 10000, "ms\n";发布于 2013-03-02 21:14:35
UUID的javadoc表示关于时间戳字段的如下内容:
60位时间戳值是从该UUID的time_low、time_mid和time_hi字段构造的。由此产生的时间戳是测量自1582年10月15日午夜以来以100纳秒为单位的。
(强调地雷)
自1970-01-01年以来,Java时间戳以毫秒为单位。为了从UUID获得一个有意义的数据,您需要做两件事:从100 10转换到1ms精度(除以10000)和从1582-10-15转换到1970-01-01,这可以通过添加一个常量值来完成。
WolframAlpha tells us ( 1582-10-15 )对应于-12219292800的一个UNIX时间戳,因此要获得正确的日期,必须将12219292800添加到除以10000后得到的毫秒数。
作为附带说明:
时间戳值仅在具有版本1的基于时间的UUID中有意义。如果该UUID不是基于时间的UUID,则此方法引发UnsupportedOperationException。
...so确保您的代码要么只遇到Type1UUID,要么能够处理它们没有时间戳。
https://stackoverflow.com/questions/15179428
复制相似问题