gpt4 book ai didi

具有相同日期格式的javascript日期

转载 作者:行者123 更新时间:2023-12-04 10:03:30 25 4
gpt4 key购买 nike

我在 javascript 日期中遇到了一个问题。我想做相同的日期格式 previous datestart dateExcepted Output上一个日期

12AM 之后显示 00:00:00 到 12:00:00

12PM 后显示 00:00:00 至 12:00:00

格式

previous date 2020-05-10 16:31:28

开始日期
2020-05-10 02:00:00              //sample data
2020-05-10 05:00:00

我的代码:



var currentdate = new Date();
var prevdate = new Date(); //previous date

prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));

var newprevious = GetFormattedDate(prevdate);
console.log(newprevious);

//Date format yyyy-mm-dd h:MM:ss
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}



注意:我无法更改开始日期,它是 fixed格式

我应该改变什么?有人帮我吗?

最佳答案

如果问题只是小时不是 am/pm 格式,您可以使用模运算符以这种方式修改您的函数(我还在字符串的末尾添加了 am/pm):

var currentdate = new Date();
var prevdate = new Date(); //previous date

prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));

var newprevious = GetFormattedDate(prevdate);
console.log(newprevious);

//Date format yyyy-mm-dd h:MM:ss
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();

// EDIT:
var hour = date.getHours()%12; // using the modulo operator, you convert the hours to a range between 0 and 12

if (hour == 0) {
hour = 12;
}

var timeOfDay = "am";

if (date.getHours() >= 12) {
timeOfDay = "pm";
}

hour = ("0" + hour).slice(-2);

// END EDIT

var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " " + timeOfDay;
}

关于具有相同日期格式的javascript日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61711827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com