Long Lý
Long Lý

Reputation: 57

new Date("YYYY/MM") not work on IE 11

In my project, i use js code below to take date with date input only year and month:

var current_time = new Date(current); 

with current data is something like this: "2017/04" It work perfect on chrome but on IE 11, i get invalid date for current_time. Can your guys help to to take date form data which only has year and month like this on IE? Thankyou.

Upvotes: 1

Views: 9547

Answers (3)

warl0ck
warl0ck

Reputation: 3464

In order to create the date by passing the month and year to dateObject you can do:

current = '2017/04';
current = current.split("/")
var date = new Date(current[0], current[1]);
// it will return the date object where date is set as the first day of the month
console.log(date)

which will give you the date object set to the first day of the month.

If you want to get the current month and year you can do:

var year = new Date().getFullYear();
var month = new Date().getMonth() + 1;
date = year + '/' + month;
console.log(date);

Upvotes: 0

Nima Hakimi
Nima Hakimi

Reputation: 1392

Dates should be formatted according RFC 2822 or ISO 8601 So if you use '-' instead of '/ it will work every where.

console.log(new Date("2017-04"))

if you want to still have your date with '/' you can do this

console.log(new Date("2017/04".replace(/\//g, "-")));

Upvotes: 4

Gaurav Chaudhary
Gaurav Chaudhary

Reputation: 1501

The format you are using is not a standard format of date. Non standard date formats cause problems on various browsers like IE, safari, etc.

Use this method. It will work on all IE as well

Run it on chrome and IE. Here in this snippet, it will give one month less since stack snippet is using a different library for date parsing.

var input = "2017/04"
var year = input.split("/")[0]

// indexing starts with 0
var month = parseInt(input.split("/")[1],10) -1 

var date = new Date(year,month)
console.log(date)

This is what it will output on browsers including IE

Sat Apr 01 2017 00:00:00 GMT+0530 (India Standard Time)

Upvotes: 0

Related Questions