var someDate = new Date(dateString);
someDate = someDate.getTime();
Answer from CrayonViolent on Stack Overflowvar someDate = new Date(dateString);
someDate = someDate.getTime();
You can use Date.parse(date).
function epoch (date) {
return Date.parse(date)
}
const dateToday = new Date() // Mon Jun 08 2020 16:47:55 GMT+0800 (China Standard Time)
const timestamp = epoch(dateToday)
console.log(timestamp) // => 1591606075000
Videos
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
It's easy, new Date() just takes milliseconds, e.g.
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
@Parth Trivedi i made two function for you.
$(document).ready(function () {
alert("Date to Epoch:" + Epoch(new Date()));
alert("Epoch to Date:" + EpochToDate(Epoch(new Date())));
});
//Epoch
function Epoch(date) {
return Math.round(new Date(date).getTime() / 1000.0);
}
//Epoch To Date
function EpochToDate(epoch) {
if (epoch < 10000000000)
epoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds)
var epoch = epoch + (new Date().getTimezoneOffset() * -1); //for timeZone
return new Date(epoch);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
const epochToDateHuman = ({epochTime=0})=>{
const valueConvert = 60000 // Base convert to Minutes to milliseconds
const milliseconds = 1000
const zone = (new Date().getTimezoneOffset() * -1 ) * valueConvert // Return subtract time zone
const newEpoch = epochTime * milliseconds // Convert new value in milliseconds
const dateConvert = new Date(newEpoch + zone) // New Date + Zone
return dateConvert}
const epoch = 1619456956
epochToDateHuman({epoch})
This arrow function epochToDateHuman, receives as parameters named epochTime that you want to convert to a zone date, The const valueConvert is the basis for converting the zone obtained in minutes to Milliseconds, because Date (). getTimezoneOffset () returns your zone time difference in minutes and when we receive in epochTime we convert them to milliseconds multiplying by the constant milliseconds, like this we obtain newEpoch with a new value in milliseconds and zone in negative milliseconds that will be subtracted from newEpoch that passed to a new Date, we obtain the value for the zone of the date... Happy hacking
Zellathor!