Convert datetime string to timestamp (seconds) using JavaScript

peterking1697923543 peterking1697923543
Blog
Convert datetime string to timestamp (seconds) using JavaScript
// Define a function that takes a datetime string as an argument
const datetimeToTimestamp = (datetime) => {
  // Check if the argument is a string
  if (typeof datetime !== 'string') {
    // If not, throw an error
    throw new Error('Argument must be a string');
  }
  // Use Date.parse() to parse the datetime string and return the number of milliseconds since January 1, 1970, 00:00:00 UTC
  const timestamp = Date.parse(datetime);
  // Check if the timestamp is valid
  if (isNaN(timestamp)) {
    // If not, throw an error
    throw new Error('Invalid datetime format');
  }
  // Divide the timestamp by 1000 and round it to the nearest integer
  const seconds = Math.round(timestamp / 1000);
  // Return the seconds
  return seconds;
};

// Test the function with some examples
console.log(datetimeToTimestamp('2023-04-05T16:25:03+02:00')); // 1680942303
console.log(datetimeToTimestamp('2023-04-05')); // 1680873600
console.log(datetimeToTimestamp('2023-04-05T16:25:03Z')); // 1680935103
console.log(datetimeToTimestamp('2023-04-05T16:25:03')); // NaN
console.log(datetimeToTimestamp(42)); // Error: Argument must be a string

Comments (0)

U
Press Ctrl+Enter to post

No comments yet

Be the first to share your thoughts!