views:

309

answers:

4

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 I 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))
A: 

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.

fuzzy lollipop
A: 

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.

Michael Myers
Hmm, someone upvoted and then took it back. Am I wrong?
Michael Myers
+1  A: 

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")

mbaird
A: 

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
Dennis Williamson