0

I have this yest_date variable in javascript

var yest_date = "Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)"

I want this variable 'yest_date' to be in this format and the value is.

 20161212

Can someone let me know how to achieve this.

1
  • You have a string, just reformat it. Commented Dec 13, 2016 at 23:39

3 Answers 3

2

I would suggest use moment.js. It is a very good library to handle any date time related problem http://momentjs.com/

var yest_date = moment("Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)")
console.log(yest_date.format("YYYYMMDD"))

If you don't want to add an extra library then you can use the classic string concat

let yest_date = new Date("Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)")
console.log(`${yest_date.getFullYear()}${yest_date.getMonth() + 1}${yest_date.getDate()}`)
Sign up to request clarification or add additional context in comments.

2 Comments

i am getting error when i use this ---> ${yest_date.getFullYear()}${yest_date.getMonth() + 1}${yest_date.getDate()}
What is the version and type is your browser? Can you provide the code and the full error log? It works on chrome for me.
1

Simply convert your string into an actual Date, then use the Date getter methods to extract the values you want into a formatted string:

let yest_date = "Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)"
let date = new Date(yest_date);
console.log(`${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`)

5 Comments

Hamms- wat is the code inside console.log ? its cryptic. can you please explain the $ sign in there
It's simply a template literal
i am getting invalid character when i use as it is whatever values are present inside console.log
Are you running the code in a browser or with node on the server side?
running the code in a browser. using tfs of visual studio to write the js code
1

You can do the following:

const date = new Date('Mon Dec 12 2016 15:33:41 GMT-0800 (Pacific Standard Time)')

const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();

const formattedDate = `${year}${month}${day}`;

console.log(formattedDate);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.