JavaScript/jQuery - 从 24 小时日期时间字符串转换为 12 小时日期格式?
JavaScript/jQuery - Convert from 24 Hr Datetime String to 12Hr Date format?
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
this.outDate = function()
{
return getJustTime(startDateTime,timeZone);
}
function getJustTime(startDateTime,timeZone)
{
outDt = new Date(startDateTime.replace(/ /g,'T'));
return outDt;
}
**Expected Output**
this.outDate = "10.30 PM CDT";
我有两个带有 24 小时日期时间字符串的变量,我想将其转换为 12 小时格式的日期字符串。我错过了什么?
P.S : 我不能使用任何日期时间库。
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
var slot='AM';
var a = startDateTime.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
if(c[0]>12){
slot='PM';
c[0] = c[0] - 12;
}
var date = c[0]+'.'+c[1]+' '+slot+' '+timeZone ;
console.log(date);
只写你自己的。 date 对象非常有用。
function am_or_pm (date) {
var date_obj = new Date(date);
var hours = date_obj.getHours();
var morn_or_night;
// I wouldn't do this in production, but this is to make my logic really clear - I would probably use a conditional operator here.
// Handling Midnight
if (hours === 0) {
hours = 12;
morn_or_night = 'AM';
// Handling noon
} else if (hours === 12) {
morn_or_night = 'PM'
} else if (hours > 12) {
hours = hours - 12;
morn_or_night = 'PM';
} else {
morn_or_night = 'AM';
}
return hours.toString()+':'+date_obj.getMinutes()+' '+morn_or_night;
}
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
this.outDate = function()
{
return getJustTime(startDateTime,timeZone);
}
function getJustTime(startDateTime,timeZone)
{
outDt = new Date(startDateTime.replace(/ /g,'T'));
return outDt;
}
**Expected Output**
this.outDate = "10.30 PM CDT";
我有两个带有 24 小时日期时间字符串的变量,我想将其转换为 12 小时格式的日期字符串。我错过了什么?
P.S : 我不能使用任何日期时间库。
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
var slot='AM';
var a = startDateTime.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
if(c[0]>12){
slot='PM';
c[0] = c[0] - 12;
}
var date = c[0]+'.'+c[1]+' '+slot+' '+timeZone ;
console.log(date);
只写你自己的。 date 对象非常有用。
function am_or_pm (date) {
var date_obj = new Date(date);
var hours = date_obj.getHours();
var morn_or_night;
// I wouldn't do this in production, but this is to make my logic really clear - I would probably use a conditional operator here.
// Handling Midnight
if (hours === 0) {
hours = 12;
morn_or_night = 'AM';
// Handling noon
} else if (hours === 12) {
morn_or_night = 'PM'
} else if (hours > 12) {
hours = hours - 12;
morn_or_night = 'PM';
} else {
morn_or_night = 'AM';
}
return hours.toString()+':'+date_obj.getMinutes()+' '+morn_or_night;
}