简体   繁体   English

在 date-fns 中解析 function 返回前一天的值

[英]parse function in date-fns returns one day previous value

I am trying to parse date using date-fns library but getting one day previous as result.我正在尝试使用 date-fns 库解析日期,但结果是提前一天。 How can I avoid this and get the right result?我怎样才能避免这种情况并获得正确的结果?

start = '2021-08-16'
const parseStart = parse(start, 'yyyy-MM-dd', new Date());

output: output:

2021-08-15T18:30:00.000Z

We had a similar problem while trying to use the date-fns format function on a hyphened string date.我们在尝试对带连字符的字符串日期使用 date-fns 格式 function 时遇到了类似的问题。 It was subtracting one day from the date while formating.它在格式化时从日期中减去一天。 The solution was in fact to change the hypes for slashes.解决方案实际上是改变对斜线的炒作。

const dateString = '2010-08-03'
const date = new Date(dateString.replace(/-/g, '/'))

Not to have this timezone overhead I'd suggest formatting your date string into ISO string and then using parseISO function of date-fns.不要有这个时区开销我建议将日期字符串格式化为 ISO 字符串,然后使用 date- parseISO的 parseISO function。

Like this:像这样:

import { parseISO } from 'date-fns';

const parseStringDate = (dateString: string): Date => {
  const ISODate = new Date(dateString).toISOString();
  return parseISO(ISODate);
};

parseStringDate("2021-08-19") //2021-08-19T00:00:00.000Z

I was using in a filter so the initial value was with "-" and i have to replace it for using "/" as well, it work's like a charm我在过滤器中使用,所以初始值是“-”,我也必须用“/”替换它,它就像一个魅力

filters: { formatedDate(value) { value = value.replaceAll('-', '/') return format(new Date(value), 'd MMM') } },

and append it in html with a pipe like this和 append 它在 html 中带有这样的 pipe

{{ date | {{ 日期 | formatedDate }}格式化日期 }}

so the output on the screen was所以屏幕上的 output 是

日月

for a string '2022-10-21'对于字符串 '2022-10-21'

None of the solutions worked for me, because the timezone was still not being unconsidered.没有一个解决方案对我有用,因为时区仍然没有被忽视。 Instead, I used:相反,我使用了:

import { isValid } from 'date-fns' 

let removeTimezone = (date) => {
   date = new Date(date);
   return new Date(
     date.valueOf() + date.getTimezoneOffset() * 60 * 1000
   );
};
   
const date = '2023-01-22'
const dtDateOnly = removeTimezone(date)
if(!isValid(dtDateOnly)) console.log("cannot convert to date")
else console.log(dtDateOnly)

This worked for me (v.2+):这对我有用(v.2+):

// wrong:
const date = format(new Date('2021-10-01'),'dd/MM/yyyy')
console.log(date) // "30/09/2021"

// ok:
const date = format(new Date('2021/10/01'),'dd/MM/yyyy')
console.log(date) // "01/10/2021"

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

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