如何格式化dateTime [英] How to format a dateTime
问题描述
03/11/2012 09:37 AM
这是我如何获取当前DateTime的功能。
函数getCurrentDateTime()
{
var currentTime = new Date()
//日期
var month = currentTime.getMonth()+ 1;
if(month< 10){
month =0+ month;
}
var day = currentTime.getDate();
var year = currentTime.getFullYear();
//时间
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if(minutes< 10){
minutes =0+ minutes;
}
if(hours> 11){
var dateString = month +/+ day +/+ year ++ hours +: +分钟++PM;
test = new Date(dateString);
return dateString;
} else {
var dateString = month +/+ day +/+年++小时+:+分钟++AM;
return dateString;
}
}
你可以看到它如何回一个字符串但是当我想要隐藏这个功能的日期时。我得到这个格式星期五五月11 2012 09:37:00 GMT + 0200(浪漫夏令时)
date = new Date dateString);
这样我就无法计算。
请问如何获得当前日期,以便我可以进行支票?
Javascript提供非常有限的功能,用于开箱即用的日期。使用外部库,如 momentjs 。
例如,您的函数将被减少到
var stringDate = moment()。format(DD / MM / YYYY HH:mm A) ;
您可以将其转换为当前时间与
var earlierDate = moment(stringDate,DD / MM / YYYY HH:mm A);
if(earlyDate.valueOf()< moment()。valueOf()){
//更早确定
}
Okay I have the following problem. I want to get the current dateTime and then want do check if a date that I enter is bigger than the current DateTime. The format of my dateTime should look like this.
03/11/2012 09:37 AM
Here is the function how I get the current DateTime.
function getCurrentDateTime()
{
var currentTime = new Date()
// Date
var month = currentTime.getMonth() + 1;
if (month < 10){
month = "0" + month;
}
var day = currentTime.getDate();
var year = currentTime.getFullYear();
// Time
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10){
minutes = "0" + minutes;
}
if(hours > 11){
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "PM";
test = new Date(dateString);
return dateString ;
} else {
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "AM";
return dateString;
}
}
As you can see how it gives back a string. But when I want to covert it to a date with this function. I get this format Fri May 11 2012 09:37:00 GMT+0200 (Romance Daylight Time)
date = new Date(dateString);
And with this I can't calculate.
Could anybody help me how I can get the current date in this format so that I can do the check?
Kind regards.
Javascript provides very limited functionality for working with dates out of the box. Use an external library like momentjs.
For example, your function would be reduced to
var stringDate = moment().format("DD/MM/YYYY HH:mm A");
And you could convert that and compare it to the current time with
var earlierDate = moment(stringDate, "DD/MM/YYYY HH:mm A");
if (earlierDate.valueOf() < moment().valueOf()) {
// earlier indeed
}
这篇关于如何格式化dateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!