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

 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. Thank in advance

Answers:

Answer

You said you want to convert from "dd/MM/yyyy to yyyy-MM-dd". JavaScript's Date constructor will always take the first two digits as a month.

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?
Answer

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/

Basically, you have 3 methods and you have to combine the strings for yourself:

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>

check this answer link

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.