javascript: changing date format but not to string

by Dave   Last Updated February 16, 2019 04:26 AM - source

Is there a way to change the format of a date object, but keep it as a date and not a string? I have a function that converts a new Date() object into the following format:

function formatDate(date) {

    var monthNames = [
        "January", "February", "March",
        "April", "May", "June", "July",
        "August", "September", "October",
        "November", "December"

    var day = date.getDate(), 
            monthIndex = date.getMonth(),
            year = date.getFullYear();

    return monthNames[monthIndex].substr(0,3) + ' ' + day + ', ' + year;

However, this converts the date into a string. I want to change the formatting so that my date appears as Feb 15, 2019, but want to keep it as a date object so it sorts in chronological order instead of alphabetical. Is this possible?

Answers 1

Rendering the date in the required format and sorting based on the date object is perfectly possible by using $filter.

More information is available here:

If you want to get the formatted date in Javscript,

function getFormattedDate(dateObj) {
    return $filter('date')(dateObj, 'mediumDate');

In other case, if we want to use this in HTML directly:

<span>{{ dateObj | date:'mediumDate'}}</span>

Here is the Plnkr example.

February 16, 2019 04:24 AM

Related Questions

Js Calculate every day between two dates

Updated September 29, 2019 22:26 PM

Using dateMath for elasticSearch query

Updated October 01, 2017 18:26 PM