简体   繁体   English

将日期字符串转换为日期 object?

[英]Convert date string to date object?

Can someone help me:有人能帮我吗:

I need to create the following.我需要创建以下内容。

Sunday 4 October 08.30 - 10.30 CET 10 月 4 日星期日 08.30 - 10.30 CET

Underneath this tough, I need to be able to display the local timezone??在这艰难之下,我需要能够显示当地时区??

Can someone please advise me on the best approach and can I do this with moment.js?有人可以建议我最好的方法吗?我可以用 moment.js 做到这一点吗?

Thanks,谢谢,

You will first need to include moment-timezone to figure out what "CET" means.您首先需要包含时刻时区以弄清楚“CET”的含义。 Standard moment does not know how to convert named timezones to offsets.标准时刻不知道如何将命名时区转换为偏移量。

  1. Now, you need to use a regular expression to parse the meaningful pieces of information from your date range.现在,您需要使用正则表达式来解析日期范围内有意义的信息。
  2. Once you have pulled out the information, reconstruct the pieces into a start and end date string.提取信息后,将这些片段重构为开始和结束日期字符串。
  3. Parse the date strings relative to the time zone.解析相对于时区的日期字符串。

I displayed the moment date objects in ISO 8601 format, so they will be in GMT (2 hours behind CET).我以 ISO 8601 格式显示了时刻日期对象,因此它们将使用 GMT(比 CET 晚 2 小时)。

 const grammar = /^(\w+) (\d+) (\w+) (\d+\.\d+) - (\d+\.\d+) (\w+)$/; const inputFormat = 'dddd D MMMM HH.mm' const input = 'Sunday 4 October 08.30 - 10.30 CET' const m = input.match(grammar); const startDateInput = `${m[1]} ${m[2]} ${m[3]} ${m[4]}`; const endDateInput = `${m[1]} ${m[2]} ${m[3]} ${m[5]}`; const timezone = m[6]; console.log(`Input (Start Date): ${startDateInput}`); console.log(`Input (End Date): ${endDateInput}`); const startDate = moment.tz(startDateInput, inputFormat, timezone); const endDate = moment.tz(endDateInput, inputFormat, timezone); console.log(`Output (Start Date): ${startDate.toISOString()}`); console.log(`Output (End Date): ${endDate.toISOString()}`);
 .as-console-wrapper { top: 0; max-height: 100%;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>

I am not sure your exact question.我不确定你的确切问题。 You can use JavaScript Date Class.您可以使用 JavaScript 日期 Class。

//This will return time, "Mon Aug 10 2020 19:46:31 GMT+0530 (India Standard Time)"
const timeZone = /\((.*)\)/.exec(new Date().toString())[1];

// Here you can calculate offset hours
const offsetHours = new Date().getTimezoneOffset() / 60;

//This is the best way, beacuse sometimes offsethours might be wrong due to daylight saving rules
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

在此处输入图像描述 And there are different ways to format a string and for other calculation.并且有不同的方法来格式化字符串和进行其他计算。 Hope this will solve your problem.希望这能解决您的问题。

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

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