我需要将mm-dd-yyyy hh:mm:ss转换为更容易更换的形式。
例如: " 12-30-2017 06:10:54"到12月12日下午6:10"使用javascript。
有人帮忙。
答案 0 :(得分:1)
使用JavaScript Date()
对象。
输入要格式化为new Date(date)
var date = "12-30-2017 06:10:54"
。
new Date("12-30-2017 06:10:54") // Sat Dec 30 2017 06:10:54 GMT+0000 (GMT Standard Time)
请注意,时区可能因设备和位置而异。
然后,您可以将其转换为字符串并将其拆分以显示相关信息。
答案 1 :(得分:1)
如果您真的不想使用moment.js
将此格式解析为日期数据类型
let dt = '12-30-2017 06:10:54';
dt = dt.split(' ');
let [date, time] = [dt[0].split('-').map(Number), dt[1].split(':').map(Number)];
let d = new Date(date[2], date[0] - 1, date[1], time[0], time[1], time[2], 0);
将其转换为您的格式
function myDate(date) {
let hh = date.getHours();
let ampm = hh >= 12 ? 'PM' : 'AM';
mm = date.getMinutes();
let time = hh + ':' + mm + ampm;
let monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
let dd=ordinal_suffix_of(date.getDate());
let month=monthNames[date.getMonth()];
let dt=dd+' '+month;
return dt+' '+time;
}
<强>样本强>
let dt = '12-30-2017 06:10:54';
dt = dt.split(' ');
let [date, time] = [dt[0].split('-').map(Number), dt[1].split(':').map(Number)];
let d = new Date(date[2], date[0] - 1, date[1], time[0], time[1], time[2], 0);
function myDate(date) {
let hh = date.getHours();
let ampm = hh >= 12 ? 'PM' : 'AM';
mm = date.getMinutes();
let time = hh + ':' + mm + ampm;
let monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
let dd = ordinal_suffix_of(date.getDate());
let month = monthNames[date.getMonth()];
let dt = dd + ' ' + month;
return dt + ' ' + time;
}
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
console.log(myDate(d));
&#13;
答案 2 :(得分:0)
使用Momen.js
转换日期/时间格式(https://momentjs.com/)
1.安装yarn add moment
2. import moment from "moment";
console.log(
"Conversion: ",
moment(new Date()).format("Do MMMM h:mm a")
);
输出: 12月30日下午7:37