Search code examples
angulardatepickercalendarbootstrap-datepickerdaterangepicker

Angular2 date range picker format date string


I am using this calendar on my Angular2/Spring web application:

https://www.npmjs.com/package/ng2-daterangepicker

http : // www. daterangepicker . com/

I am facing the problem of formatting the date output. From the official documentation this is the object that is responsible for formatting the date:

locale.format: "MM/DD/YY" // which returns 05/13/2017

However, I am interested in more user-friendly output. Something like: May 2017.

How am I suppose to do this? Where can I found letters that can format my date in Javascript (like this in PHP: http://php.net/manual/en/function.date.php).

Thank you very much for the replies.


Solution

  • If I were you I'd save myself the hassle of working with Dates in Javascript and download Moment.js. If you're using npm you can install it with

    npm install moment --save
    

    Dates are a pain to work with in vanilla JS so moment is a really powerful library that lets you "parse, validate, manipulate, and display dates and times" super easily. To use it in your Angular2 Component you just need to import it in your component after downloading it.

    import * as moment from 'moment';
    

    Then you can format your output date using the format() function.

    let rangePickerValue = new Date(); // example date
    moment(rangePickerValue).format('MMMM YYYY'); // May 2017
    

    You can see what sort of time and date output options there are in moment's documentation: here. For examlpe, MMMM outputs the full month's name (January, February, March...) while MMM prints (Jan, Feb, Mar...).