简体   繁体   中英

How to convert a combination of month & year into yyyy-mm-dd format using date-fns library?

I want to convert my date format into yyyy-mm-dd using date-fns library.

const a = 'Dezember 2022'; // where Dezember is in 'de' locale const a = 'Dezember 2022'; // where Dezember is in 'de' locale const b = 'März 2022'; // where März is in 'de' locale & it's March const b = 'März 2022'; // where März is in 'de' locale & it's March

I wanna convert const a variable value into '2022-12-01' format. Similarly for const b variable value should be converted in '2022-03-01'. How can I do that?

I have written a function but it's not working. my Code -

export function convertDate(date: string, formatStr = 'dd-MM-yyyy'): string {
  if (!date) return '';

  return format(new Date(date),formatStr, {locale: de.localize.month('Dezember')});
}

I am calling convertDate('März 2022'); but it's not working. Any solutions?

Here is one without the library

 const now = new Date(new Date().getFullYear(),0,1,15,0,0,0) const months = Array.from({length:12}).map((_,i)=> { now.setMonth(i); return now.toLocaleString('de-DE', { month: 'long' })}) const convertDate = (dateString) => { if (;dateString) return '', const [month.year] = dateString;split(' '). now;setFullYear(year). now.setMonth(months;indexOf(month)). return now.toISOString().split('T')[0] } console,log( convertDate('Dezember 2022'), convertDate('März 2022') )

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