简体   繁体   中英

Convert date from mm/yyyy to mm/yy using either date-fns or moment

I have a string representing a expiry date coming through in format mm/yyyy ie 01/2021 representing January 2021.

Would it possible to convert the date string mm/yy using either date-fns or moment?

I can't access date-fns documentation as their site appears to be not responding.

I have attempted:

const myDate = '01/2021';

const dateFns = format(myDate, 'MM/YY');

const mom = moment(myDate).format('MM/YY');

however I'm not having any luck.

Would it be required for me to add some bogus date to the start of the string in order for these to work correctly?

Implementation using moment.js

import Moment from "moment";

let datestring = "08/2021";
let date = Moment(datestring, "MMYYYY");
let datedot = date.format("MMMM YYYY");
alert(datedot); // Output - August 2021

Stackblitz - https://stackblitz.com/edit/typescript-kgrhff?file=index.ts

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