获取Javascript日期格式为2011-04-01 [英] get Javascript date formatted as 2011-04-01
问题描述
我看过:如何获取格式化日期时间,如2009-05-29 21:55:57使用javascript?
但我需要0之前的单数字日期(我需要2011-04-01,而不是2011-4-1)
but I do need the 0's before a single digit date(I need 2011-04-01, not 2011-4-1)
我不喜欢为这个添加另一个不必要的插件,所以如果有在js / jquery中的内置函数或SIMPLE函数可以做到这一点,我很好。我希望它不会导致10行功能,只是为了检查这个月是否是单数,然后添加一个零。
I don't like to add another unnecessary plugin for this one so if there's a builtin function or SIMPLE function in js/jquery that could do this, I'm good. I do hope it will not result to a 10 line function just to check if the month was singular and then add a zero to it.
基本上,我正在使用AnyTime js(http://www.ama3.com/anytime/)插件,但如果我的开始日期不是yyyy-mm-dd的形式,它会抛出错误。我的起始默认值是now,所以我试图将一个新的Date()转换成该格式。任何帮助?
Basically, I am using the AnyTime js (http://www.ama3.com/anytime/) plugin but it throws an error if my starting date was not in the form "yyyy-mm-dd". My starting default value is "now" so I am trying to convert a new Date() to that format. Any help?
注意
请不要提供插件的链接,因为我希望得到一个非常简单的解决方案。我发现使用插件来修复一个插件并不是很干净。
NOTE please don't give links of plugins as i was hoping for a REALLY simple solution. i find that using a plugin just to fix a plugin isn't actually very clean.
推荐答案
function getFormattedDate() {
var date = new Date();
var str = date.getFullYear() + "-" + getFormattedPartTime(date.getMonth()) + "-" + getFormattedPartTime(date.getDate()) + " " + getFormattedPartTime(date.getHours()) + ":" + getFormattedPartTime(date.getMinutes()) + ":" + getFormattedPartTime(date.getSeconds());
return str;
}
function getFormattedPartTime(partTime){
if (partTime<10)
return "0"+partTime;
return partTime;
}
这篇关于获取Javascript日期格式为2011-04-01的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!