3

given time_cancel = 2019-01-06T23:29:35.000Z, would like to format it to month dd, yyyy (in this example, it is January 06, 2019)

In the following code, I have to write 12 if else block to convert mm to month i.e. in this case, is to convert 01 to January.

is there a better /faster way to convert time_cancel to format month dd, yyyy in Javascript or Typescript/es6/react. Thanks in advance!

let date = time_cancel.split("T")[0];
var dateArray = date.split("-"); 
var month;

// 12 if else code
if(dateArray[1]=='01') month='January';
else if(dateArray[1]=='02') month='February';
 ....
else if (dateArray[1]=='12') month='December;

var res=month+" "+dateArray[2]+", "+dateArray[0];
IntFooBar
  • 174
  • 3
  • 18
user21
  • 1,261
  • 5
  • 20
  • 41
  • Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – str Jan 17 '19 at 08:11
  • Possible duplicate of [Current time formatting with Javascript](https://stackoverflow.com/questions/14638018/current-time-formatting-with-javascript) – IntFooBar Jan 17 '19 at 08:29
  • Use the below package, you can do a lot of other manipulation on date and time. https://www.npmjs.com/package/moment – nitinsridar Jan 17 '19 at 09:01

3 Answers3

5

.toLocaleDateString() can give you DD Month YYYY, but it doesn't let you customise the order. I would be very tempted to stick with this default behaviour, but you can chop it up if your really must. You still profit from the locale awareness and translations...

const formattedDate = new Date("2019-01-06T23:29:35.000Z")
.toLocaleDateString({},
  {timeZone:"UTC",month:"long", day:"2-digit", year:"numeric"}
  )
  console.log(formattedDate)
const sp = formattedDate.split(' ')
console.log(`${sp[1]} ${sp[0]}, ${sp[2]}`)
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
2

You can make an array like

let months = ["January", "February", "March", /*etc*/];

Read about getMonth()

lets say you have a date let date = new Date();

Simply do let m = date.getMonth() and it will return values from 0 to 11.

Then you can just say months[m] and you will get your desired date.

Here is a JSFiddle, feel free to edit the months in date to check it's validity. http://jsfiddle.net/snqwg7vd/

Mirakurun
  • 4,859
  • 5
  • 16
  • 32
  • but new Date() is returning current date and time, I'd like to just past the above previous time stamp in the function (not the current timesteamp) – user21 Jan 17 '19 at 08:29
  • just npm install moment and then import moment from 'moment' in React but it says module not found. – user21 Jan 17 '19 at 08:34
  • I just put `new Date();` to get an example date. If you already have a date, you can skip that part. – Mirakurun Jan 17 '19 at 08:43
  • Tried the following code but it returns 0 but would like it to return January. time_cancel = 2019-01-06T23:29:35.000Z let month = new Date(time_cancel).getMonth(); – user21 Jan 17 '19 at 08:46
  • Of course it returns 0, because it's January. I told you it returns values from 0 to 11, where 0 is January and 11 is December. Let me create a fiddle for you. – Mirakurun Jan 17 '19 at 08:56
  • Check the JSFiddle and see what it returns now. – Mirakurun Jan 17 '19 at 09:00
  • I don't like to be discouraging, but people have to stop creating arrays of months. There are enough in the world already. – bbsimonbb Jan 17 '19 at 10:37
1

function formatraw(date, format, utc) {

    let raw = new Date(date.split(" ").join("T"));

    let res = format.slice();

    const MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    const ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    function ii(i, len) {
        let s = i + "";
        len = len || 2;
        while (s.length < len) s = "0" + s;
        return s;
    }

    const y = utc ? raw.getUTCFullYear() : raw.getFullYear();
    res = res.replace(/(^|[^\\])yyyy+/g, "$1" + y);
    res = res.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
    res = res.replace(/(^|[^\\])y/g, "$1" + y);

    const M = (utc ? raw.getUTCMonth() : raw.getMonth()) + 1;
    res = res.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
    res = res.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
    res = res.replace(/(^|[^\\])MM/g, "$1" + ii(M));
    res = res.replace(/(^|[^\\])M/g, "$1" + M);

    const d = utc ? raw.getUTCraw() : raw.getDate();
    res = res.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
    res = res.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
    res = res.replace(/(^|[^\\])dd/g, "$1" + ii(d));
    res = res.replace(/(^|[^\\])d/g, "$1" + d);

    const H = utc ? raw.getUTCHours() : raw.getHours();
    res = res.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
    res = res.replace(/(^|[^\\])H/g, "$1" + H);

    const h = H > 12 ? H - 12 : H == 0 ? 12 : H;
    res = res.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
    res = res.replace(/(^|[^\\])h/g, "$1" + h);

    const m = utc ? raw.getUTCMinutes() : raw.getMinutes();
    res = res.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
    res = res.replace(/(^|[^\\])m/g, "$1" + m);

    const s = utc ? raw.getUTCSeconds() : raw.getSeconds();
    res = res.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
    res = res.replace(/(^|[^\\])s/g, "$1" + s);

    let f = utc ? raw.getUTCMilliseconds() : raw.getMilliseconds();
    res = res.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
    f = Math.round(f / 10);
    res = res.replace(/(^|[^\\])ff/g, "$1" + ii(f));
    f = Math.round(f / 10);
    res = res.replace(/(^|[^\\])f/g, "$1" + f);

    const T = H < 12 ? "AM" : "PM";
    res = res.replace(/(^|[^\\]){TT}/g, "$1" + T);
    res = res.replace(/(^|[^\\]){T}/g, "$1" + T.charAt(0));

    const t = T.toLowerCase();
    res = res.replace(/(^|[^\\]){tt}/g, "$1" + t);
    res = res.replace(/(^|[^\\]){t}/g, "$1" + t.charAt(0));

    let tz = -raw.getTimezoneOffset();
    let K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
    if (!utc) {
        tz = Math.abs(tz);
        let tzHrs = Math.floor(tz / 60);
        let tzMin = tz % 60;
        K += ii(tzHrs) + ":" + ii(tzMin);
    }
    
    res = res.replace(/(^|[^\\])K/g, "$1" + K);

    const day = (utc ? raw.getUTCDay() : raw.getDay()) + 1;
    res = res.replace(new RegExp(dddd[0], "g"), dddd[day]);
    res = res.replace(new RegExp(ddd[0], "g"), ddd[day]);

    res = res.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
    res = res.replace(new RegExp(MMM[0], "g"), MMM[M]);

    res = res.replace(/\\(.)/g, "$1");

    return res;
}

console.log(formatraw("2019-01-06T23:29:35.000Z","MMMM dd, yyyy"))
Vadim Hulevich
  • 1,803
  • 8
  • 17