微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Java从UUID中提取日期?

如何将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";

解决方法

UUID的javadoc说明了以下关于时间戳记字段的信息:

The 60 bit timestamp value is constructed from the time_low,time_mid,and time_hi fields of this UUID. The resulting timestamp is measured in 100-nanosecond units since midnight,October 15,1582 UTC.

(强调我的)

自1970年1月1日起,Java时间戳记以毫秒为单位.为了从UUID获得有意义的日期,您需要做两件事情:从100ns转换为1ms精度(除以10000),并从1582-10-15转换为1970-01-01,您可以执行通过添加常数值.

WolframAlpha tells us,1582-10-15对应于-12219292800的UNIX时间戳,所以要获得正确的日期,您必须添加12219292800到除以10000后获得的毫秒数.

作为附注:

The timestamp value is only meaningful in a time-based UUID,which has version type 1. If this UUID is not a time-based UUID then this method throws UnsupportedOperationException.

…所以确保你的代码只有遇到类型1 UUID的,或者可以处理它们没有时间戳.

原文地址:https://www.jb51.cc/java/123357.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐