开发者

How do you convert date taken from a bash script to milliseconds in a Java program?

I am writing a piece of code in Java that needs to take a time sent from a bash script and parse the time to milliseconds. When I check the millisecond conversion on the date everything is correct except for the month I have sent which is January instead of March.

Here is the variable 开发者_如何学GoI create in the bash script, which later in the script I pass to the Java program:

TIME=`date +%m%d%Y_%H:%M:%S`

Here is the Java code which parses the time to milliseconds:

String dt = "${scriptstart}";
java.text.SimpleDateFormat scriptStart = new java.text.SimpleDateFormat("MMDDyyyy_HH:mm:ss");
long start = scriptStart.parse(dt).getTime();

The goal of this statement is to find the elapsed time between the start of the script and the current system time.

To troubleshoot this I printed out the two:

 System Time = 1269898069496 (converted = Mon Mar 29 2010 16:27:49 GMT-0500 (Central Daylight Time))
 Script Start = 03292010_16:27:45
 Script Start in Milli = 1264804065000 (Converted = Fri Jan 29 2010 16:27:45 GMT-0600 (Central Standard Time))


According to the Epoch Converter web site both those timestamps in ms are printing the correctly represented time. The DD should be dd in your string formatter.


You need to use "dd" instead of "DD". You are using "Day in year" instead of "Day in month".

So change this: new java.text.SimpleDateFormat("MMDDyyyy_HH:mm:ss")

to this: new java.text.SimpleDateFormat("MMddyyyy_HH:mm:ss")


According to the Javadocs, you should be using "MMddyyyy" instead of "MMDDyyyy". "DD" is the day of the year, not the day of the month.

That apparently causes it to override the month that it already parsed, which in turn causes the output to be January 29 -- the 29th day of the year.


The date command (which is independent of Bash, by the way) will print the time in seconds since the Epoch without having to convert it using Java:

scriptstart=$(date +%s)
echo ${scriptstart}     # example: 1269903559
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜