请这个" 15:00"我是一个字符串。
我想把它转换成下午3点;意味着我想将它从GMT转换为EST。
请告诉我如何通过内置功能或创建自己的功能来实现?
答案 0 :(得分:0)
我写了一个能满足你需求的功能:
function convertTime(time){
var arr = time.split(':'); //splits the string
var hours = Number(arr[0]);
var minutes = Number(arr[1]);
var AMPM = "";
if(hours>=12 && hours != 24){ //checks if time is after 12 pm and isn't midnight
hours = hours-12;
AMPM = " pm";
}else if(hours<12){//checks if time is before 12 pm
AMPM = " am";
}
if(hours==24){//special case if it is midnight with 24
hours = hours - 12;
AMPM = " am"
}
if(hours==0){//special case if it is midnight with 0
hours = hours + 12;
}
//converts the Numbers back to a string
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10){//checks if the hours is 2 places long and adds a 0 if true
sHours = "0" + sHours;
}
if(minutes<10){//checks if the minutes is 2 places long and adds a 0 if true
sMinutes = "0" + sMinutes;
}
var result = sHours + ":" + sMinutes + AMPM; //sets string back together
return result;
}