Multiple ways to format a js timestamp into a date format

  • 2020-03-27 00:06:49
  • OfStack

Js needs to convert the timestamp to a normal format.
So let's start with the first one
function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/,' '); 

As a result,
December 23, 2010 10:53
The second,
function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17)} 

What if you want something in this format?
The 2010-10-20 10:00:00
Look at the code below
function getLocalTime(nS) { 
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/ years | month /g, "-").replace(/ day /g, " "); 

Or you could write it like this
function formatDate(now) { 
var year=now.getYear(); 
var month=now.getMonth()+1; 
var date=now.getDate(); 
var hour=now.getHours(); 
var minute=now.getMinutes(); 
var second=now.getSeconds(); 
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
var d=new Date(1230999938); 

Okay, problem solved
Here's the thing to note
Do not pass the Date(or Date) in the string
You can use the replace method
As follows:

Related articles: