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

DeathAlpha
  • 61
  • 9

2 Answers2

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()]);
Marcelo Vismari
  • 1,147
  • 7
  • 15
  • @NishantSingh use an additional function like [this](https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php) – Marcelo Vismari May 02 '19 at 17:02
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>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • I updated the week in answer, if you dont want the month var date = moment.unix(creation_time).format('YYYY,w, ddd'); – Hien Nguyen May 02 '19 at 16:36