Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change time format to 24 hours in javascript

Tags:

I have a time format like: 12/16/2011 3:49:37 PM and I got this format by:

var newDate = new Date(timeFromat);
timeFormat = newDate.toLocaleString();

My actual format was GMT and I converted it to my bowers time by using the code above.

and I want to change it to 24h time format so I want this date to be changed like: 12/16/2011 15:49:37 and I want to do it in javascript.

Thats what I did

var firstPartOftimeFormat = timeFormat.substring(0,9);
var secondPartOftimeFormat = timeFormat.substring(10,20);

but it does not work when the date format is like: 3/16/2011. but the following part works.

var time = $("#starttime").val();
var hours = Number(secondPartOftimeFormat.match(/^(\d+)/)[1]);
var minutes = Number(secondPartOftimeFormat.match(/:(\d+)/)[1]);
var AMPM = secondPartOftimeFormat.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);

Can you suggest other approach?

thanks

like image 502
user3409650 Avatar asked Mar 12 '14 09:03

user3409650


People also ask

Which option is used to change the new time format for 24-hour format?

Start Control Panel, and then under Clock, Language, and Region, click Change date, time or number formats. On the Formats tab, under Date and time formats, do one of the following: To change to 24-hour format, on the Short time drop-down list, select HH:mm and on the Long time drop-down list, select HH:mm:ss.

How do you display javascript datetime in 24 hour AM PM format?

You have the formatAMPM function, which will take a JavaScript date object as a parameter. Call getHours to get the hours in the 24-hour format in the function and minutes to get the minutes. Then, create the ampm variable and set it to am or pm depending on the value of hours.


1 Answers

use dateObj.toLocaleString([locales[, options]])

Option 1 - Using locales

var date = new Date();
console.log(date.toLocaleString('en-GB'));

Option 2 - Using options

var options = { hour12: false };
console.log(date.toLocaleString('en-US', options));
like image 130
LiranBo Avatar answered Oct 10 '22 05:10

LiranBo