var myString = '01 Jan 1970 00:00:00 GMT'; var myDate = new Date(Date.parse(myString));
What’s happening here? A string is defined containing a date. A new Date object is then defined using the result of the Date.parse function, which takes the date string and converts it to Unix time.
It’s a bit unwieldy, and worst of all, it only works when the date string adheres to a specific format.
The Smart Way – Using Moment.js
Moment.js is thoroughly documented – I won’t re-interpret any of it here. It’s well-written, easy to understand, and kept up-to-date with the latest package features:
I’ll provide a quick example on parsing a date from a string, as that’s why we’re here – but the complete documentation contains a full list of available tools for parsing dates:
First, you’ll need to include Moment.js in your HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
var myString = '12/11/2021'; moment(myString, 'DD/MM/YYYY');
It’s that easy – simply call moment() and pass the string and format your date is in, and it will do the rest.