最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - replacing moment data with date-fns - Stack Overflow

programmeradmin2浏览0评论

we are migrating from moment library to date-fns in the project on which I am working.

I am trying to find a soution to replace it with date-fns but I am not successful:

          timezone: moment().format('Z')

If I replace it with:

          timezone: format(new Date(),'Z')

Then It is not working. If anyone know how to solve it then please let me know. Thanks

we are migrating from moment library to date-fns in the project on which I am working.

I am trying to find a soution to replace it with date-fns but I am not successful:

          timezone: moment().format('Z')

If I replace it with:

          timezone: format(new Date(),'Z')

Then It is not working. If anyone know how to solve it then please let me know. Thanks

Share Improve this question asked May 19, 2022 at 10:09 Cluadia HeddaCluadia Hedda 1412 silver badges10 bronze badges 1
  • 2 date-fns is using unicode token for format function which is different from Moment.js and other libraries. Please refer this document for more details: date-fns/v2.28.0/docs/format – Priyank Kachhela Commented May 19, 2022 at 10:23
Add a ment  | 

1 Answer 1

Reset to default 5

It can be done like this:

     timezone: format(new Date(),'XXX')

It might be helpful for you, I change moment data in my project like this:

Moment data:

  import moment, { Moment } from 'moment/moment';

  const DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss[Z]';

  moment().endOf('day').format(DATE_FORMAT);

  moment().subtract(13, 'days');

  moment().subtract(1, 'months');

  moment().subtract(1, 'years');

  moment().subtract(1, 'years').startOf('year');

  moment().endOf('year').format(DATE_FORMAT);

  function getStartDate(date: Moment): string {
    return date.startOf('day').format(DATE_FORMAT);
  }

To

date-fns data:

  import { 
    endOfDay,
    endOfYear, 
    format,
    startOfDay,
    startOfYear, 
    subDays, 
    subMonths ,
    subYears } from 'date-fns';

  const DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

  format(endOfDay(new Date()), DATE_FORMAT);

  subDays(new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate())),
    13);

  subMonths(new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate())),
    1);

  subYears(new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate())),
    1);

  startOfYear(subYears(new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate())),
    1));


  format(endOfYear(new Date()), DATE_FORMAT);

  function getStartDate(date: Date): string {
     return format(startOfDay(date), DATE_FORMAT);
  }
发布评论

评论列表(0)

  1. 暂无评论