We already saw an example of how to convert date to string. Let’s see two approaches to converting string to date.
Using Date constructor
string – It takes a string as a YYYY/MM/DD format string. If we pass different formats that do not follow the ISO 8601 format, it will return an invalid date.
const d = new Date("2022/4/18"); console.log(d) console.log(d.getDate()); console.log(d.getFullYear());
Mon Apr 18 2022 00:00:00 GMT+0530 (India Standard Time) 18 2022
In the example we use getDate() and getFullYear() method. And it’s a lot of methods that are very useful while we are working with data.
Using moment.js library
- stringDate: We need to provide a string that we want to convert into a date.
- formatString: You can provide the format of our string.
If you are using simple HTML, you need to add these two script tags to your html file. After adding this scripts tag, you can easily use the moment.js.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> <script type="module" src="index.js"></script>
For Framework, library
If you are using react, view, or any front-end library, you need to install it using npm.
npm i moment --save
import moment from 'moment'; let string = "04-19-2022"; let dateObj = moment(string, "MM-DD-YYYY"); let stringvalue = dateObj.format("YYYY-MM-DD"); console.log(stringvalue);
In the above example, we pass a string and its format so it will return a date object.
In this dateObj, there are lots of methods we can use. But, first, we convert our mm-dd-yyyy format string into the yyyy-mm-dd format.
If you are building a production-level project and there are many uses for this type of date conversion, you should use the moment library.