我想用这种格式转换字符串日期" 3/25/2018 11:51:46 PM" 到这样的24小时语言环境格式" 10/05/2018在08:51:46" (法文格式)
当我插入这种日期" 3/25/2018 11:51:46 PM"我得到了这个" 10/05/2018在08:51:46"
这是我目前的代码:
String.prototype.toDate = function(format) {
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat = format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = `enter code here`
normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex > -1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex > -1 ? dateItems[monthIndex] - 1 : today.getMonth() - 1;
var day = dayIndex > -1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex > -1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex > -1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex > -1 ? dateItems[secondsIndex] : today.getSeconds();
if ((this.split(" ")[2] == "PM") && hour < 12) {
hour = hour + 12;
} else if ((this.split(" ")[2] == "AM") && hour == 12) {
hour = hour - 12;
}
console.log(year + " " + month + " " + day + " " + hour + " " + minute + " " + second);
return new Date(year, month, day, hour, minute, second);
};
logd = "3/25/2018 11:51:46 PM".toDate("mm/dd/yyyy hh:ii:ss");
console.log(logd.toLocaleString());
&#13;
答案 0 :(得分:1)
不确定为什么每个人都想使用图书馆,为什么不只是混合使用toLocaleDateString
和toLocaleTimeString
:
var options = { hour12: false };
var date = new Date("3/25/2018 11:51:46 PM");
console.log(`${date.toLocaleDateString("fr-FR")} ${date.toLocaleTimeString("fr-FR", options)}`);
// or just use toLocaleString:
console.log(date.toLocaleString("fr-FR", options));
&#13;
答案 1 :(得分:-1)
使用Moment.JS,一个基于日期和时间的项目的强大工具:
你可以在你的用例和一些样本
之下
console.log(moment().format('DD/MM/YYYY [at] HH:mm:ss'))
console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));
console.log(moment().format('dddd'));
console.log(moment().format("MMM Do YY"));
console.log(moment().format('YYYY [escaped] YYYY'));
console.log(moment().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment-with-locales.min.js"></script>