1

I have a small need where i want to convert a timestamp stored in a variable say doc.creation_time to a format [year,month,day]

example:

doc.creation_time = 1537492812 this should be converted to [2018,38,Fri]

Can someone help

4
  • Fri is not defined? May 2, 2019 at 13:52
  • 5
    new Date(doc.creation_time * 1000) (it takes milliseconds so we multiply it by 1000) to make a Date object, then you can get all kinds of stuff out of it: developer.mozilla.org/ru/docs/Web/JavaScript/Reference/…
    – Walk
    May 2, 2019 at 13:55
  • Month 38???????
    – some
    May 2, 2019 at 14:08
  • Do you want ISO-week or not? Do your weeks start with Sunday or Monday?
    – some
    May 2, 2019 at 20:34

2 Answers 2

5

var creation_time = 1537492812;
var date = new Date(creation_time * 1000);
var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

// UTC
console.log(date.getUTCFullYear(), date.getUTCMonth() + 1, weekday[date.getUTCDay()]);

// Local
console.log(date.getFullYear(), date.getMonth() + 1, weekday[date.getDay()]);

1
2

You can use momentjs for your requirement

var creation_time = 1537492812;
//var date = moment.unix(creation_time).format('YYYY,MM,ddd');
var date = moment.unix(creation_time).format('YYYY,w,ddd');
var result = date.split(',');
console.log(result);

var creation_time = 1537492812;
//var date = moment.unix(creation_time).format('YYYY,MM,w, ddd');
var date = moment.unix(creation_time).format('YYYY,w,ddd');
var result = date.split(',');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

1
  • I updated the week in answer, if you dont want the month var date = moment.unix(creation_time).format('YYYY,w, ddd'); May 2, 2019 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.