简体   繁体   中英

simpledateformat coverting 24hr time to minutes

I'm wanting to convert 24hr time, eg 0748 or 748, into minutes. For some reason it is converting it to only 128 minutes when it should be 468 minutes.

double time = 748;
//parse time into SimpleDateFormat to easily extract hours and minutes
Date date_time_to_minutes = new SimpleDateFormat("HHmm").parse(String.valueOf(time));
//hours extracted from time
double extracted_hours = Integer.parseInt(new SimpleDateFormat("HH").format(date_time_to_minutes));
//minutes extracted from time
double extracted_minutes = Integer.parseInt(new SimpleDateFormat("mm").format(date_time_to_minutes));
//converts the extracted hours into minutes and adds it to the extracted minutes
double minutes = extracted_hours * 60 + extracted_minutes;

The HHmm date format is taking not 7 , but 74 as the number of hours, leaving 8.0 as the minutes. Inserting this code reveals what is happening.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date_time_to_minutes));

Output:

1970-01-04 02:08:00

That is 3 days, 2 hours, and 8 minutes past the epoch (1970-01-01 00:00:00), aka 74 hours and 8 minutes.

This declaration of date_time_to_minutes succeeds, presumably because of the leading "0" I added.

Date date_time_to_minutes = new SimpleDateFormat("HHmm").parse("0748");

Output:

1970-01-01 07:48:00

The solution is to ensure that you have a leading zero if the hours value is less than 10.

Date date_time_to_minutes = new SimpleDateFormat("HHmm").parse(
  new DecimalFormat("0000").format(time)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM