This question already has answers here:
Parse date without timezone javascript
(16 answers)
Closed 4 years ago.
Input: I have a date string: "2018-11-30T01:00:00+11:00"
Usecase: I need to convert it into Date object using plain js or with any library.
Result: I should receive a date object with date part as "2018-11-30" and time part as "1:00".
Please help. I've tried every solution but the time always changes to match my machine's timezone. I don't want that behavior neither do I want to do complicated time conversions on my backend.
This is the solution that I came up with for this problem which actually works.
library used: momentjs with plain javascript Date class.
Step 1.
Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):
const dateMoment = getMomentFromIsoString(date);
Step 2.
Extract hours and minutes values from the previously created moment object:
const hours = dateMoment.hours();
const mins = dateMoment.minutes();
Step 3.
Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):
const dateObj = dateMoment.toDate();
Step 4.
Manually set the hours and minutes extracted in Step 2.
dateObj.setHours(hours);
dateObj.setMinutes(mins);
Step 5.
dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.
Hope this helps.
Related
This question already has an answer here:
Why moment.js treats dash differently from slash?
(1 answer)
Closed last month.
I am trying to save a date and time for different time zones. I have changed my time zone in my chrome dev tools for testing purposes as follows
So for testing, I am trying to save a date time for London as '2023/04/21 23:55' when I save this datetimeoffset into my DB it gets stored as '2023-01-30T23:55:00+02:00'
but now when I try to read the format the date is as follows
var test = Moment(date); //'2023-01-30T23:55:00+02:00'
test = test.utc(true);
var format = "yyyy/MM/DD HH:mm";
return test.format(format);
it returns the date 2023/01/30 21:55. Why is it removing the 2 hours?
The issue is that your datetimeoffset has a timezone associated with it (+02:00). The 2023-01-30T23:55 part of your timestamp is not UTC time, it is local time, and the +02:00 signifies the offset of that timezone.
I'm not sure how you're saving that time in the first place, you probably forgot to specify the timezone as UTC. For example, if the date was created with Moment('2023-01-30T23:55:00'), then it that time will be intepreted as 23:55:00 on 2023-01-30 in the system's timezone, not UTC. To fix this, you need to use the Moment.utc('2023-01-30T23:55:00').
This question already has answers here:
Use JavaScript to convert a date string with timezone to a date object in local time
(3 answers)
Closed 5 months ago.
My app gets an array of events from an external source. Each event has a start date like 20220925000000 +0000. The format is YYYYMMDDHHMMSS and the last part is timezone which is not always +0000.
I need to store the events and show the right start date and time to each user (Around the globe) based on their timezone. I've searched and read some SO questions but it is still confusing to me. What is the correct approach?
// first parse the date using a regex:
const [m, year, month, day, hours, minutes, seconds, timezone] = '20220925000000 +0000'.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}) (\+\d{4})/);
// Then log it with proper input format for date object:
const str = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${timezone}`;
// pass it to Date constructor and call `toLocaleString()` to get user's local format.
console.log(new Date(str).toLocaleString());
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
Closed 5 years ago.
Pretty straightforward issue, but I haven't found any information on this after looking around a bunch.
Essentially, I want to convert a series of UTC dates (e.g. "1505952000") into regular date strings (e.g., "9/21"), to use today as an example.
For some reason, however, .toDateString() is erroring out as "not a function" when I try to run it. How do I make this simple conversion work?
Here's my code, and I've console-logged day.dt to ensure that it's a valid UTC date when it runs:
let dt = day.dt.toDateString();
UTC var stored in seconds from Jan. 1, 1970.
So to convert it back to the local date time, use this snippet:
var d = new Date(0);
d.setUTCSeconds(1505952000);
console.log(d);
OR
var d = new Date(1505952000 * 1000); // Because this constructor takes miliseconds.
console.log(d);
This question already has answers here:
Moment js date time comparison
(9 answers)
Closed 7 years ago.
I am using moment.js in my application, I pass my date in a particular format to moment.js and it compares it with the system time and give me the pretty time format, like this:
moment(time, "YYYY-MM-DD HH:mm:ss.SSSSSS").fromNow();
Here the time is given by me as a timestamp in the specified format.
My problem is that fromNow() function takes the system date and not the server date. So, if a user uses his phone with 5 min delay time in his system he will get 4 min ago as the latest updated cards.
I want to compare "time" that I pass with the server time, that also will be passed by me.
You could pass in 2 dates from your server: the existing timestamp, and the server's "now" timestamp.
Then (assuming your server passes in its timestamp in the same format) you can use .from() instead of .fromNow() do:
moment(time, "YYYY-MM-DD HH:mm:ss.SSSSSS").from(serverTime, "YYYY-MM-DD HH:mm:ss.SSSSSS");
If this is the only thing you're using the timestamp for, you could just have the server calculate & return the delta directly (let's call it serverDeltaMs) & format that using moment.duration(serverDeltaMs).humanize().
This question already has answers here:
Create a Date with a set timezone without using a string representation
(29 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
I'm in the process of building out a timeline featured for my web app and I am manipulating the elements added to the timeline by using:
var time_going = new Date(data2.time_going * 1000),
time_going_hour = time_going.getHours(),
time_going_minutes = time_going.getMinutes(),
left_position = (time_going_hour * width_by_hour) + (time_going_minutes * width_by_minute);
The problem is that the left_position is different based on your current timezone because the new date function is returning different information. Is there anyway to force the time to always be consistent to New York time?
The data2.time_going is in Unix Timestamp and is set to 1368687333 for example.
As you probably already know, UNIX "Epoch" times have no timezone. This makes dealing with UNIX timestamps easy, because you never have to keep track of what timezone they are in.
Similarly, JavaScript Date objects are timezone independent. When you call getHours(), that method is doing the time-offset math for the timezone of the current machine.
So instead of always using New York time, you may better off doing all your time math using the UTC timezone. In other words, instead of using the locale-dependent getHours() and getMinutes(), try using getUTCHours() and getUTCMinutes(). So long as you are initializing your Date object with a UNIX Epoch time, those methods will always return the same value no matter the timezone of the machine they are running on.