JavaScript 如何更改日期现在格式



我遇到了javascript日期的问题。我想更改日期的格式

this.setState({ 
current: Date(Date.now()),

}, 1000);

//convert minutes 
//if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00 
//if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
var slotTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ;  //10:30

输出:

Thu May 14 2020 10:00:30 GMT+0500 (Pakistan Standard Time)

预期

10:00:52 AM
10:30 AM

我应该更改什么?

您可以简单地使用日期toLocaleTimeString()方法,例如:

const current = new Date()
const timestring = current.toLocaleTimeString()
console.log( timestring )   //=> 10:47:52 AM

toLocaleTimeString()方法返回一个字符串,其中包含日期的时间部分的语言敏感表示形式。


要仅获取hh:mm a格式,您可以将选项对象传递给toLocaleTimeString()方法,如下所示:

const current = new Date()
const timestring = current.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
console.log( timestring )   //=> 10:50 AM


setState

this.setState({
current: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
var date=new Date();    
console.log(date.getHours() + ":" + date.getMinutes()+ ":" + date.getSeconds() + " " + date.getHours()<12 ? 'AM' : 'PM'}`);

输出 : 11:9:37 AM

date.getHours((<12 在上午 12 点到上午 11:59 之间在上午 11:59 之间产生结果,在 11:59 之后,它会导致下午

最新更新