简体   繁体   中英

Convert date string to date object?

Can someone help me:

I need to create the following.

Sunday 4 October 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?

Thanks,

You will first need to include moment-timezone to figure out what "CET" means. 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).

 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.

//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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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