-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunixtime
106 lines (84 loc) · 2.56 KB
/
unixtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!perl -w
# -*-perl-*-
# $Id$
#
use strict;
=head1 NAME
unixtime - convert between integer and string time formats
=head1 SYNOPSIS
unixtime 123456789
unixtime '1/1/99 23:11:11'
unixtime 'Wed Jan 14 23:50:34 1999'
unixtime '2451666 79199'
unixtime 2451666 79199
=head1 DESCRIPTION
L<unixtime> converts unix seconds since the epoch into L<ctime> if passed an
integer. If the integer is greater than 10 digits, the last 3 digits are
assumed to be milliseconds and are truncated.
L<unixtime> converts L<ctime> format into seconds since the unix epoch. The
L<ctime> format may be missing the day of week and the year (assumed to be this
year).
L<unixtime> converts slash-separated ("mm/dd/[yy]yy") format into seconds since
the unix epoch. The date may be followed by a time in 24 hour format.
=head1 OPTIONS
=over 4
=item -gmt
print output in GMT (default is local). If Bivio::Type::Date, then
will always print gmt.
=back
=head1 BUGS
None so far!
=head1 COPYRIGHT
Copyright (c) 1999 Bivio, Inc. All rights reserved.
=head1 AUTHOR
Rob Nagler <[email protected]>
=cut
use Time::Local qw(timelocal timegm);
use Bivio::Type::DateTime;
@ARGV || die("usage: unixtime [-gmt] times...\n");
my($GMT) = 0;
if ($ARGV[0] =~ /^-g(mt)?$/) {
$GMT++;
shift(@ARGV);
}
while (@ARGV) {
my($t) = shift(@ARGV);
my(@args);
# String of digits is assumed to be unix time. If there are more
# than 10 digits, then it is assumed to be (java) milliseconds,
# strip last 3 digits.
if ($t =~ /^\d{7}$/ && @ARGV && $ARGV[0] =~ /^\d{1,5}$/) {
$t .= ' ' . shift(@ARGV);
}
elsif ($t =~ /^\d+$/) {
length($t) > 10 && $t =~ s/...$//;
print scalar($GMT ? gmtime($t) : localtime($t)), "\n";
next;
}
if ($t =~ /^\d+ \d+$/) {
my($m) = $GMT || $t =~ / 79199$/ ? 'to_string' : 'to_local_string';
print Bivio::Type::DateTime->$m($t), "\n";
next;
}
# 1/1/99 or 1/1/1999 or <date> 1:1:1 (24 hour only)
elsif ($t =~ m,^(\d+)/(\d+)/(\d+)(\s+(\d+):(\d+):(\d+))?$,) {
@args = (defined($4) ? ($7, $6, $5) : (0, 0, 0),
$2, $1 - 1, $3 < 38 ? $3 + 100 : $3);
}
# Wed Jan 14 23:50:34 or Wed Jan 14 23:50:34 1999
elsif ($t =~ m,^(\w+\s+)?(\w+)\s+(\d+)\s+(\d+):(\d+):(\d+)(\s+(\d+))?$,) {
my($mon) = 0;
my($m);
foreach $m (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)) {
$m eq $2 && last;
$mon++;
}
@args = ($6, $5, $4, $3, $mon,
defined($8) ? ($8 > 1900 ? $8 - 1900 : $8)
: ($GMT ? gmtime(time) : localtime(time))[5]);
}
else {
die("unknown time format\n");
}
print $GMT ? timegm(@args) : timelocal(@args), "\n";
}