I am looking for a simple way to convert a javascript date to unix timestamp
.
Here’s an example: JSFiddle.
I am looking for a simple way to convert a javascript date to unix timestamp
.
Here’s an example: JSFiddle.
Using Date.parse() is simple and effective:
const dateString = "2012.08.10";
const date = new Date(dateString);
const timestamp = date.getTime();
console.log(timestamp); // Unix timestamp (milliseconds)
Date.parse() automatically converts a valid date string into a Date object, and getTime() provides the Unix timestamp in milliseconds. Easy and works well for most date formats.
A direct approach is to use new Date() :
const dateString = "2012.08.10";
const date = new Date(dateString);
const timestamp = date.getTime() / 1000; // Convert milliseconds to seconds
console.log(timestamp); //
With the Unix timestamp (seconds), you can directly create a Date object from a date string and use getTime() to get the timestamp in milliseconds. Dividing by 1000 converts it to seconds, which is the typical Unix timestamp format.
If your date string isn’t automatically recognized by JavaScript, you can manually parse it as a fallback to handle custom date formats :
const dateString = "2012.08.10";
const [year, month, day] = dateString.split('.').map(Number);
const date = new Date(year, month - 1, day); // Month is 0-based
const timestamp = date.getTime() / 1000;
console.log(timestamp); // Unix timestamp (seconds)
If the date format is non-standard or not recognized by JavaScript, manually splitting and parsing the date string ensures compatibility.