How to extract dates from UUIDs using Java?

How to convert UUID to date format 2011-04-22?

For example, I have such a UUID

118ffe80-466b-11e1-b5a5-5732cf729524.

How do I convert this to date format?

I tried

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();
        }

Output: 4294744 / 11 / 02

The same case applies to 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";

Solution

The Javadoc of UUID describes the following information about the timestamp field:

(emphasize my)

Since January 1, 1970, java time stamps are in milliseconds To get a meaningful date from UUID, you need to do two things: convert from 100ns to 1ms precision (divide by 10000) and from 1582-10-15 to 1970-01-01. You can do this by adding constant values

Wolfram Alpha tell us, 1582-10-15 corresponds to the UNIX timestamp of - 12219292800, so to get the correct date, you must add 12219292800 to the number of milliseconds obtained by dividing by 10000

As a note:

... so make sure your code only encounters type 1 UUIDs, or can handle them without timestamps

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>