如何用javascript格式化日期

How to format dates in javascript

本文关键字:日期 格式化 javascript 何用      更新时间:2023-09-26

我从文本框中选择此日期,并希望格式化为以下格式: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

有什么想法吗?我有点注意到,如果我像2012年7月3日那样使用美国,它就可以了。提前感谢

您说过要从"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​

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>

检查这个答案链接