我从文本框中选择这个日期,我想格式化为这种格式:yyyy-MM-dd 所以从dd / MM / yyyy到yyyy-MM-dd
var startDate = document.getElementById('ctl00_PlaceHolderMain_ctl00_Date').value;
var s = new Date(startDate);
alert(startDate); //which prints out 7/03/2012
//when i use the below to try and format it to : yyyy-MM-dd which is what i want
var scurr_date = s.getDate();
var scurr_month = s.getMonth();
scurr_month++;
var scurr_year = s.getFullYear();
出于某种原因,我得到了:
var fstartdate = scurr_year + "-" + scurr_month + "-" + scurr_date;
//Output:2012-7-3
instead of : 2012-3-7
also fi i pick a date like 31/12/2011
i get : 2013-7-12
任何想法该怎么做。如果我像03/07/2012那样使用美国,我会注意到它的工作正常。 提前谢谢
答案 0 :(得分:0)
http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
和这个
http://www.elated.com/articles/working-with-dates/
基本上,你有3种方法,你必须自己组合字符串:
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
<script type="text/javascript">
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
</script>
检查此答案link
答案 1 :(得分:0)
你说你想要从“dd / MM / yyyy转换为yyyy-MM-dd”。 JavaScript的Date
构造函数总是将前两位数作为一个月。
一些正则表达式可能会对您有所帮助:
function fix_date (str) {
var re = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
str = str.replace(re, function (p1, p2, p3, p4) {
return p4 + '/' + p3 + '/' + p2;
});
return str;
}
var start_date = '7/03/2012';
var new_date = fix_date(start_date);
console.log(new_date); // 2012/03/7