Jump to content

Date.setMonth(1)


davej
 Share

Recommended Posts

Seeing a strange problem...

 

setMonth(1) is giving me March, which can be explained if setDate(1) has not been executed, but...

<!DOCTYPE html><html><head><script>window.onload = init;function init(){var d = new Date();d.setFullYear(2014);d.setMonth(1);d.setDate(1);document.getElementById("demo").innerHTML= d;}</script></head><body><div id="demo"></div></body></html>

...in both FF and Chrome I get...

 

Sat Mar 01 2014 15:11:03 GMT-0600 (Central Standard Time)

 

I am running Win 7 Pro 64-bit and the clock and calendar seem to be correct.

Edited by davej
Link to comment
Share on other sites

At the moment setMonth is called the date is set to today's date (31). Call setDate first and it will work. Look at this example to see for yourself:

<!DOCTYPE html><html><head><title>Test</title><meta charset="UTF-8"><script>window.onload = init;function init(){var d = new Date();d.setFullYear(2014);d.setMonth(1);d.setDate(1);document.getElementById("demo").innerHTML= d;var d2 = new Date();d2.setFullYear(2014);d2.setDate(1);d2.setMonth(1);document.getElementById("demo2").innerHTML= d2;}</script></head><body><div id="demo"></div><div id="demo2"></div></body></html>
Link to comment
Share on other sites

Hi,

This will write the date in US and UK format to a div. You could chop off the bits you dont need.

 

 

This is months.js.

 

function init(){ var panel= document.getElementById("panel"); var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]; var months = ["Jan", "feb", "Mar", "apr", "May", "Jun", "Jul", "Aug", "Sep", " Oct", "Nov", "Dec"]; var now = new Date(); var yy = now.getFullYear(); var mm = now.getMonth(); var dd = now.getDate(); var dy = now.getDay(); mm = months[mm]; dy = days[dy]; var str = dy + ", " + mm + " " + dd + ", " + yy; panel.innerHTML += "US Date string: " + str; str = dy + ", " + dd + " " + mm + ", " + yy; panel.innerHTML += "<br>UK Date String: " + str;}document.addEventListener("DOMContentLoaded", init, false);

 

You need an HTML doc with a div id="panel".

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...