Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...