How can I change a date string into a date object?

Seeking assistance:

I am looking to generate the following:

Sunday 4 October 08.30 - 10.30 CET

Additionally, I would like to show the local timezone information below this line.

Could someone recommend the most effective method for achieving this? Can it be done using moment.js?

Thank you,

Answer №1

To understand the meaning of "CET," you must first include moment-timezone. Standard moment lacks the capability to convert named timezones into offsets.

  1. Next, utilize a regular expression to extract important information from your date range.
  2. After retrieving the necessary data, assemble it into a start and end date string.
  3. Interpret the date strings based on the specified time zone.

The moment date objects are presented in ISO 8601 format for display, adjusting them to 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>

Answer №2

I'm not entirely clear on your question, but one solution could be using the JavaScript Date Class.

// This code snippet will display the current time with timezone information
const timeZone = /\((.*)\)/.exec(new Date().toString())[1];

// Calculate offset hours based on timezone
const offsetHours = new Date().getTimezoneOffset() / 60;

// Utilize Intl.DateTimeFormat() to get the resolved timezone
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

https://i.sstatic.net/tSi1J.png There are various methods for string formatting and other calculations as well. Hopefully, this provides a solution to your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

mention a particular anchor by clicking on it to refresh the webpage

Can a webpage automatically navigate to a specific anchor/tag when reloaded in the browser? Thanks in advance I came across this method: window.location.reload(); However, I'm searching for a solution that can detect the reload and then run a basi ...

Detecting collisions between a ThreeJS camera and a 3D object model using raycasting

I'm trying to navigate a camera through a scene where I've loaded an object as a mesh, and I'm attempting to detect collisions between the camera and the walls of the object. I've been inspired by this threejs example: , and I've ...

Struggling with overlaying Bootstrap modals on top of each other

This idea is inspired by the topic Multiple modals overlay I am working on developing a folder modal that allows users to either 1) open an existing file or 2) create a new file within each folder modal. To see how it functions, please run the code below ...

Get a specific value from a JSON object

Within my Calendar, there is a code snippet that includes an Object and JSON data. This JSON object contains various properties such as [{"Date":"17-3-2015","Event":"Test drive","Participants":"John, George","Description":"Testing a new F30"}, {"Da ...

using withDefaultPrettyPrinter() does not result in the output being automatically formatted

I am facing an issue while saving JSON data to a file. Below is the code I am using for serialization: private String serializeToJson(T item) { String json; ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); try { ...

What is the best way to ensure that my transitionend event is triggered?

I'm currently exploring the <progress> element and attempting to incorporate a CSS transition to achieve a smooth progress bar effect as its value increases. Despite my efforts, I can't seem to trigger JS after the transitionend event occur ...

What could be the reason for the malfunction of this AngularJS data binding feature?

I am trying to create an angularjs filter that outputs HTML, similar to what is discussed in the link, but I am encountering issues. In my HTML code, I have: <ul> <li ng-repeat="book in books | filter:query"> {{book.title}} ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

I have the ability to effectively open a modal whenever necessary, but I struggle with closing it afterwards

I've been working on implementing a React bootstrap modal, and while I can successfully open it when needed, I'm running into issues with closing it. I'm not sure what mistake I might be making. Here's my markup: <Modal show={this. ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

The Quirks of jQuery's .load() Method

On my website, I am incorporating a basic jQuery script to load content from one part of a webpage into the 'display container' on the same page. The content being loaded consists of multiple divs enclosed within an outer <div> that is hid ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

choosing a date range

My goal was to determine the number of days between a "fromDate" and a "toDate," with the restriction that the user should not be able to select a date range of more than 90 days. I am utilizing the Dojo framework to create a date calendar. Below is the co ...

Verify whether the JSON file has an empty string within a bash script

Greetings, the structure of my Json file is as demonstrated below: { "num_sensor" : 1, "J2" : {"B" : "sensor0", "A" : "sensor1", "D" : "sensor2" , "C" : " ...

Triggering a server-side event handler in ASP.NET using client-side JavaScript

I need help with implementing a countdown timer in JavaScript. When the timer reaches 0 seconds, I would like the page to trigger the button1_click event handler. Here's the scenario: I am working on a quiz engine where the quiz responses need to be ...

The useEffect function completely overwrites the existing store

My Redux store consists of 3 reducers: let reducers = combineReducers({ config: configReducer, data: dataReducer, currentState: gameStateRecuder}) let store = createStore(reducers, applyMiddleware(thunkMiddleware)); Initially, each reducer in the store i ...

Guide to generating a date span using PHP

I attempted to create a PHP script to display dates from January 29, 2017 to December 29, 2017. However, I encountered an issue with February having only 28 days. Is there a way to still display the dates correctly, even if it means skipping ahead to the 2 ...

What is the best way to showcase an image using Next.js?

I'm having a problem with displaying an image in my main component. The alt attribute is showing up, but the actual image is not appearing on the browser. Can someone please point out what I might be doing wrong? import port from "../public/port. ...