简体   繁体   English

将带时区的日期字符串转换为格式 yyyy-mm-dd

[英]Convert date string with timezone to format yyyy-mm-dd

Hello I was wondering is it possible to transform this Date string:您好,我想知道是否可以转换此日期字符串:

Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)

to the format of:格式为:

2000-08-12

I tried the following things:我尝试了以下内容:

 var DateInput = "Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)"; var test = new Date(DateInput); console.log(test); var convert_date = test.toString().split('-'); console.log(convert_date);

But this does not work.但这不起作用。 Can anyone explain why and help me guiding to the right direction?任何人都可以解释为什么并帮助我指导正确的方向吗?

Looks like you are really just trying to reformat the input date string (without converting to local time).看起来您真的只是在尝试重新格式化输入日期字符串(不转换为当地时间)。 Your attempt relies on Date for string parsing, which is not recommended (see JavaScript Date note regarding date string parameters ).您的尝试依赖于Date进行字符串解析,不推荐这样做(请参阅JavaScript Date note regarding date string parameters )。 It also uses toString which is implementation dependent and can't be relied on to reformat the output to a specific format like yyyy-mm-dd .它还使用toString ,它依赖于实现,不能依赖于将 output 重新格式化为特定格式,如yyyy-mm-dd

You can't just convert the date string to a Date object and then rely on methods like getDate() because those methods return values in local time which may be different than the date values you are trying to preserve from the input date string with a specific timezone.您不能只将日期字符串转换为Date object 然后依赖像getDate()这样的方法,因为这些方法返回的本地时间值可能与您尝试从输入日期字符串中保留的日期值不同特定时区。

As noted in other answers, there are lots of libraries you can use for this sort of thing.正如其他答案中所指出的,有很多库可以用于此类事情。 Otherwise, here are a couple of hacks you can try (beware, variations in your date string input format could break either of these approaches - hence the existence of the libraries).否则,这里有一些您可以尝试的 hack(请注意,日期字符串输入格式的变化可能会破坏这些方法中的任何一种 - 因此库的存在)。

Credit to @SergeyMetlov for the two digit month and date formatting .感谢 @SergeyMetlov 两位数的月份和日期格式

If your date strings are consistently formatted in the same way as your example, just parse the string and reformat the output as desired.如果您的日期字符串的格式与您的示例一致,只需解析字符串并根据需要重新格式化 output。

 const str = 'Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)'; const format = (d) => (d < 10? '0': '') + d; const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // parse date string (lazy since time parts not used) const [day, m, d, yyyy, ...time] = str.split(' '); // two digit format for month and date const mm = format(months.indexOf(m) + 1); const dd = format(d); // format date as yyyy-mm-dd const date = `${yyyy}-${mm}-${dd}`; console.log(date); // 2000-08-12

Or if you want to force the js date object to submit, then you can try something ugly like the below.或者如果你想强制 js 日期 object 提交,那么你可以尝试像下面这样丑陋的东西。 The example relies on Date.parse to parse the input date string which is not recommended since implementations may not be consistent across browsers.该示例依赖于Date.parse来解析输入的日期字符串,这是不推荐的,因为跨浏览器的实现可能不一致。 If you really wanted to do something like this you should replace Date.parse (and the clunky substr line) with some better parsing of your own.如果你真的想做这样的事情,你应该用你自己的更好的解析替换Date.parse (和笨重的substr行)。

 const str = 'Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)'; const format = (d) => (d < 10? '0': '') + d; const utc = Date.parse(str); const localoffset = new Date().getTimezoneOffset() * 60000; const operator = str.substr(28, 1); const stroffset = (() => { let offset = str.substr(29, 4) * 60000; if (operator === '-') { offset *= -1; } return offset; })(); // convert utc to "wrong" date, will look "right" when formatted const wrong = new Date(utc + localoffset + stroffset); const y = wrong.getFullYear(); const m = format(wrong.getMonth() + 1); const d = format(wrong.getDate()); const output = `${y}-${m}-${d}`; console.log(output); // 2000-08-12

This should work test.getFullYear() + "-" + test.getMonth()+1 + "-" + test.getDate()这应该工作test.getFullYear() + "-" + test.getMonth()+1 + "-" + test.getDate()

Use date-fns to manipulate dates, its very cool modern JavaScript date utility library使用date- fns 操作日期,它是非常酷的现代 JavaScript 日期实用程序库

Ex:前任:

var format = require('date-fns/format');
var result = format(new Date('Sat Aug 12 2000 00:00:00 GMT+0200 (Midden-Europese zomertijd)'),'YYYY-DD-MM');

link: https://date-fns.org/v1.29.0/docs/format链接: https://date-fns.org/v1.29.0/docs/format

I actually created this dateFormat.js to handle exactlly this sort of thing.我实际上创建了这个dateFormat.js来处理这类事情。 It extends the Date object so as long as you have included the file in your site you can use它扩展了日期 object,因此只要您将该文件包含在您的站点中就可以使用

var date = new Date(); 
date.formatDateTime('YDM')

And by using the Date object, you can also set the date you wish to format as normal.通过使用日期 object,您还可以将日期设置为正常格式。

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

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