简体   繁体   English

有没有办法在 date-fns 中反转格式?

[英]Is there a way to reverse a format in date-fns?

I am from Thailand, and wondering is there a way to reverse a format in date-fns?我来自泰国,想知道有没有办法在 date-fns 中反转格式?

For example, this function will turn "2022-09-24" to "saturday-24-september-2564"例如,这个 function 将把“2022-09-24”变成“saturday-24-september-2564”

This there a good method using date-fns to create a new function that will turn "saturday-9-september-2564" back to "2022-09-24"?这是使用 date-fns 创建一个新的 function 的好方法,它将“saturday-9-september-2564”变回“2022-09-24”?

Thank you so much in advance非常感谢你提前

//---------------- //----------------

import format from "date-fns/format";
import th from "date-fns/locale/th";
import addYears from "date-fns/addYears";

const transformDate = (d) => {
        const newDate = new Date(d);
        const year_ymd = addYears(newDate, 543);

        const urlText =
          format(newDate, "EEEE'-'d'-'MMMM") + format(year_ymd, "'-'yyyy");

        return urlText.toLowerCase();
      };

transformDate(2022-09-24);

Just the other way around it would be something like this if I'm not mistaken:如果我没记错的话,反过来它会是这样的:

import {format, addYears, parse} from "date-fns";
import {th} from "date-fns/locale/th";

const transformDate = (d) => {
        const newDate = new Date(d);
        const year_ymd = addYears(newDate, 543);

        const urlText =
          format(newDate, "EEEE'-'d'-'MMMM") + format(year_ymd, "'-'yyyy");

        console.log(urlText.toLowerCase());
      };

transformDate('2022-09-24');

const transformDate2 = (d) => {
  const parsed = parse(d, "EEEE'-'d'-'MMMM'-'yyyy", new Date(), { locale: th })
  const formatted = format(parsed, 'dd-MM-yyyy');
  console.log(formatted)
}

transformDate2('saturday-24-september-2565')

Also, 4th param in the parse method contains optional properties that could be passed.此外, parse方法中的第 4 个参数包含可以传递的可选属性。 In case you need anything more feel free to refference this picture:如果您需要更多内容,请随时参考此图片:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM