Home > Net >  JS Format 201708 into M yy format
JS Format 201708 into M yy format

Time:06-14

I have a string in this format 201708 where the first four numbers are the year and the last two the month's. The result being a date of August 2017.

My first idea was to just make it to an date but won't work for me

var formattedDate = new Date("201708")

Thanks for any help

CodePudding user response:

use substring() to split the string into year and month, then use those when calling Date().

let input = '201708';
let year = parseInt(input.substring(0, 4));
let month = parseInt(input.substring(5));
let date = new Date(year, month-1);
console.log(date);

You have to subtract 1 from month because JS counts months starting from 0.

CodePudding user response:

Separate the date with a hyphen.

let b = "201708"
let b_with_hyphen = b.substring(0, 4)   "-"   b.slice(4)
// '2017-08'

let formattedDate = new Date(b_with_hyphen)
console.log(formattedDate.toUTCString())

  • Related