[英]How to format dates in javascript
I pick this date from a textbox and i would like to format to this format: yyyy-MM-dd So from dd/MM/yyyy to yyyy-MM-dd 我从文本框中选择了这个日期,我想将其格式化为以下格式: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();
For some reason i get: 由于某种原因,我得到:
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
Any ideas what to do.I kind of notice if i use US like 03/07/2012 it kind os works ok. 任何想法怎么办。我有点通知我如果我像2012年3月7日那样使用美国,它可以正常工作。 Thank in advance
预先感谢
http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3 http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
and this 和这个
http://www.elated.com/articles/working-with-dates/ http://www.elated.com/articles/working-with-dates/
Basically, you have 3 methods and you have to combine the strings for yourself: 基本上,您有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>
You said you want to convert from "dd/MM/yyyy to yyyy-MM-dd". 您说过要从“ dd / MM / yyyy转换为yyyy-MM-dd”。 JavaScript's
Date
constructor will always take the first two digits as a month. JavaScript的
Date
构造函数始终将前两位数字作为月份。
Some regex might help you here: 一些正则表达式可能会在这里为您提供帮助:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.