Monday, April 23, 2012

How to get current date in JavaScript


How to get current date in JavaScript?



Source: Tips4all

3 comments:

  1. Your question was a little light. It's always best to say hello and explain your question rather then just "how do I do this". After all this is a community. This is why you got such harsh responses.

    Moving on. Hendrik's answer will work but probabbly isn't what you are looking for. The format is not very usable.

    I have been having the same issue and have come up with this through a lot of searching.

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
    document.write(today);


    It's quite complex but it will give you todays date in the format of mm/dd/yyyy.

    Simply change today = mm+'/'+dd+'/'+yyyy; document.write(today); to what ever format you wish.

    Hope this helps.

    ReplyDelete
  2. Try this -

    <script type="text/javascript">
    var currentDate = new Date()
    var day = currentDate.getDate()
    var month = currentDate.getMonth() + 1
    var year = currentDate.getFullYear()
    document.write("<b>" + day + "/" + month + "/" + year + "</b>")
    </script>


    The result will be like

    15/2/2012

    ReplyDelete
  3. If you want something simple pretty to the end user ...

    var objToday = new Date(),
    weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
    dayOfWeek = weekday[objToday.getDay()],
    domEnder = new Array( 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th' ),
    dayOfMonth = today + (objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder[objToday.getDate()] : objToday.getDate() + domEnder[parseFloat(("" + objToday.getDate()).substr(("" + objToday.getDate()).length - 1))],
    months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
    curMonth = months[objToday.getMonth()],
    curYear = objToday.getFullYear(),
    curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
    curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
    curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
    curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
    var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;

    ReplyDelete