[英]Convert date string to date object?
有人能帮我吗:
我需要创建以下内容。
10 月 4 日星期日 08.30 - 10.30 CET
在这艰难之下,我需要能够显示当地时区??
有人可以建议我最好的方法吗?我可以用 moment.js 做到这一点吗?
谢谢,
您首先需要包含时刻时区以弄清楚“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>
我不确定你的确切问题。 您可以使用 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.