Convert string to date or date to string in typescript/javascript with examples

String and Date manipulations in typescript

string and date are of objects in typescript which holds different values. Every application, we want to manipulate dates and convert to/from date to different types. Date objects have default current date and time in typescript. Date with default constructor returns current date time. Date object holds different timezones - GMT and UTC String is a sequence of characters enclosed in single quotes. We have a moment library to handle and manipulate Date objects using typescript and javascript. We will see the example to convert Date to string or String to Date in typescript

How to Convert String to Date in typescript? 

We have many ways to convert to String to date.

Using Date constructor

Pass string date object using Date constructor if the string date is not in date format, it returns invalid date

let dateString = '2015-10-06'   
let dateString1= '10-06-2015'   
let dateString2= 'asdfasdfasdfads'  
let newDate = new Date(dateString);  
let newDate1 = new Date(dateString1);  
let newDate2 = new Date(dateString2);  
console.log(newDate) // Tue Oct 06 2015 05:30:00 GMT+0530 (India Standard Time)  
console.log(newDate1) // Tue Oct 06 2015 00:00:00 GMT+0530 (India Standard Time)  
console.log(newDate2)//  Invalid Date  

momentjs to convert to Date from String.

strings contain date format like MM-DD-YYYY, then we have to use moment(stringDate,formatString) method for convert to a Date object.

var dateString = '08-25-2018';  
var momentVariable = moment(dateString, 'MM-DD-YYYY');  
var stringvalue = momentVariable.format('YYYY-MM-DD');   
console.log(stringvalue); // outputs 2018-08-25  

How to convert Date to String in typescript

We have many ways to achieve using toDateString() method and moment library. We will see both below with examples.

Using toDateString() method

Date object one method called toDateString() which returns date in the form of string Here is an example for Converting from Date to String

var date = new Date('2017-03-07T10:00:00');  
let str = date.toDateString();  
console.log(str) //Tue Mar 07 2017  
console.log(typeof str) // string  

Using momentjs example

Date object is created and, passing this date object to moment constructor and called format method which is parsing date as per the format described.

var date = new Date('2017-03-07T10:00:00');  
var formatted = moment(date).format('D MMMM YYYY');  
console.log('formatted' ,formatted) // outputs 7 March 2017  
console.log('formatted' ,typeof formatted) // outputs string  

The same examples will also work on javascript.

Please like or share your feedback/questions in facebook/twitter and also subscribe to email for getting web development tutorials to your email inbox.

Similar Posts