0

I need to convert the current timestamp (Eg: 1578293326452) to yyyy-mm-dd hh:mm:ss format using javascript. I obtained the current timestamp as follows:

var date = new Date();
var timestamp = date.getTime();

How can I change the format?

deHaar
  • 17,687
  • 10
  • 38
  • 51
Keekz
  • 185
  • 2
  • 10
  • `new Date().toISOString()` should give you a string in a similar format to what you're after – Nick Parsons Jan 06 '20 at 07:43
  • If that doesn't work for you, since it's not close enough, I'd suggest using moment.js. Just know it is quite a large library, there are other smaller libraries, but in general formatting dates in javasctript is not a super easy task – jgerstle Jan 06 '20 at 07:45
  • Duplicate of [Where can I find documentation on formatting a date in JavaScript?](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Sudhir Ojha Jan 06 '20 at 07:49

2 Answers2

1

function getTime(){
  var date = new Date();
  
  var year = date.getFullYear();
  var month = (date.getMonth() +1);
  var day = date.getDate();
  
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  
  return formateTime(year, month, day, hour, minute, second);
}

function formateTime(year, month, day, hour, minute, second){
  return makeDoubleDigit(year) + "-" + 
         makeDoubleDigit(month) + "-" + 
         makeDoubleDigit(day) + " " + 
         makeDoubleDigit(hour) + ":" + 
         makeDoubleDigit(minute) + ":" + 
         makeDoubleDigit(second);
}

function makeDoubleDigit(x){
  return (x < 10) ? "0" + x : x;
}

console.log(getTime())
Andam
  • 2,087
  • 1
  • 8
  • 21
-1

Maybe this is what you need

d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");

console.log(d);
irtazaakram
  • 161
  • 8