简体   繁体   中英

JS format date in date range picker

I have a daterangepicker in angular 4 and I would like to get the start Date and End Date when the date range selection is made. When I do console.log(value) it is showing the response like this:

{start: Moment, end: Moment}
    end:
    Moment
    _d : Thu Apr 19 2018 23:59:59 GMT-0500 (CDT) {}
    _i : (6) [2018, 2, 25, 12, 0, 0]
    _isAMomentObject : true
    _isUTC:false
    _isValid:true
    _locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", ordinal: ƒ, _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, …}
    _pf:{empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
    __proto__ :Object
    start: Moment
    _d: Mon Apr 09 2018 00:00:00 GMT-0500 (CDT) {}
    _i:(6) [2018, 2, 25, 12, 0, 0]
    _isAMomentObject: true
    _isUTC: false
    _isValid:true
    _locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", ordinal: ƒ, _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, …}
    _pf:
    {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -1, charsLeftOver: 0, …}
    __proto__: Object

Then I tried to use stringify and console.log(JSON.stringify(datepicker.start)); this giving me result like this: 2018-04-16T05:00:00.000Z

So I tried this:

 const date = new Date(JSON.stringify(datepicker.start));
 const date_str = moment(date).format('DD.MM.YYYY');

    console.log(date_str);

And this console is showing as invalid date.

How do I convert this into a normal date something like this: '2018-05-01' ?

If you need actual JS date object, you can use _d property of start/end like

datepicker.start._d
datepicker.end._d

This will return you JS date object and you don't need to stringify and pass to Date constructor etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM