Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

change time format to 24 hours in javascript

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...