Parse date without timezone javascript
The date is parsed correctly, it's just toString
that converts it to your local timezone:
let s = "2005-07-08T11:22:33+0000";
let d = new Date(Date.parse(s));
// this logs for me
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)"
// and something else for you
console.log(d.toString())
// this logs
// Fri, 08 Jul 2005 11:22:33 GMT
// for everyone
console.log(d.toUTCString())
Create a Date in js ignoring timezone
Yes! If you create all your Date objects using the Date.UTC function, then they will all be relative to the standard UTC timezone, even if the user's browser has a different timezone set.
For example:
var ex = new Date( Date.UTC( 2015, 3, 31 ) );
This will create a Date object for 3/31/2015 UTC
and be consistent across all browsers regardless of their default timezone.
Internally, the date inside ex
will still be converted in the user's local timezone. So if you read values from it, say the date, it will be relative to the user's browser time.
So if you need to read the time back out in UTC, you can do something like this:
ex.getUTCYear(); // 2015
ex.getUTCMonth(); // 3
ex.getUTCDate(); // 31
This will give you the value back in UTC time.
How to ignore time-zone on new Date()?
As Frz Khan pointed, you can use the .toISOString() function when returning the date from your function, but if you're seeking the UTC format, use the .toUTCString(), it would output something like Mon, 18 Apr 2016 18:09:32 GMT
function updateLatestDate(sensorsData) {
return new Date(Math.max.apply(null, sensorsData.map(function (e) {
return new Date(e.MeasureDate).toUTCString();
})));
}
Create a Date with a set timezone without using a string representation
using .setUTCHours()
it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
You cannot set it using UTC in the constructor though, unless you specify a date-string.
Using new Date(Date.UTC(year, month, day, hour, minute, second))
you can create a Date-object from a specific UTC time.
Output a "timestamp without timezone" format as date only
If you are certain the date will always be separated with an empty space then you should split the string and get the first half that contains the date.
const dateTime = '2021-08-13 01:19:26';
const getDate = dateTime => {
const [date] = dateTime.split(' ')
return date
}
console.log(getDate(dateTime))
How to ignore user's time zone and force Date() use specific time zone
A Date object's underlying value is actually in UTC. To prove this, notice that if you type new Date(0)
you'll see something like: Wed Dec 31 1969 16:00:00 GMT-0800 (PST)
. 0 is treated as 0 in GMT, but .toString()
method shows the local time.
Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.
What we need here is some formatting
var _date = new Date(1270544790922);
// outputs > "Tue Apr 06 2010 02:06:30 GMT-0700 (PDT)", for me
_date.toLocaleString('fi-FI', { timeZone: 'Europe/Helsinki' });
// outputs > "6.4.2010 klo 12.06.30"
_date.toLocaleString('en-US', { timeZone: 'Europe/Helsinki' });
// outputs > "4/6/2010, 12:06:30 PM"
This works but.... you can't really use any of the other date methods for your purposes since they describe the user's timezone. What you want is a date object that's related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it's methods.
Option 1 - a 3rd party like moment-timezone
moment(1270544790922).tz('Europe/Helsinki').format('YYYY-MM-DD HH:mm:ss')
// outputs > 2010-04-06 12:06:30
moment(1270544790922).tz('Europe/Helsinki').hour()
// outputs > 12
This looks a lot more elegant than what we're about to do next.
Option 2 - Hack up the date object
var currentHelsinkiHoursOffset = 2; // sometimes it is 3
var date = new Date(1270544790922);
var helsenkiOffset = currentHelsinkiHoursOffset*60*60000;
var userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var helsenkiTime = new Date(date.getTime()+ helsenkiOffset + userOffset);
// Outputs > Tue Apr 06 2010 12:06:30 GMT-0700 (PDT)
It still thinks it's GMT-0700 (PDT), but if you don't stare too hard you may be able to mistake that for a date object that's useful for your purposes.
I conveniently skipped a part. You need to be able to define currentHelsinkiOffset
. If you can use date.getTimezoneOffset()
on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.
Conclusion - I think especially for this purpose you should use a date library like moment-timezone.
Avoid timezone correction for JavaScript Date
Values passed to the Date constructor are treated as local, toISOString uses UTC. Unfortunately ECMAScript doesn't have a timezone–free, date–only form.
If you want to use toISOString to format the timestamp, then one solution is to parse the values as UTC initially, e.g.
sendDate(d) {
let date = new Date(Date.UTC(this.year, this.month, d));
htmx.ajax("GET", "/some/url", { values: { "date": date.toISOString() } });
}
Example:
let d = new Date()
let year = d.getFullYear();
let month = d.getMonth()
let day = d.getDate();
let date = new Date(Date.UTC(year, month, day))
// Always shows the current local date as 00:00:00Z
console.log( date.toISOString() );
Related Topics
Change Name of Uploaded File on Client
How to Find If a Text Contains Url String
Javascript Regex: Replace Hyphen Between Characters Only (Not Spaces)
Preventing Viewport Resize of Web Page When Android Soft Keyboard Is Active
Use Localstorage Across Subdomains
Refresh Leaflet Map: Map Container Is Already Initialized
How to Show an Alert After Reloading the Page in JavaScript
How to Assign Empty Value to Select Dropdown
Number Value Format With Comma and Two Decimal Points
Cannot Open Local File - Chrome: Not Allowed to Load Local Resource
How to Build Pdf File from Binary String Returned from a Web-Service Using JavaScript
Regular Expression Which Allow Only Characters or Space
Delete Span Tag Along With Text in HTML Permanently
Reactjs - Multiple If Conditions Inside Map Function
Trying to Add Image to Pdf Using Jspdf
Javascript: How to Read a Hand Held Barcode Scanner Best
How to Push Array to Json Object in Angular
How to Redirect to Another Page in Reactjs When a If Condition Is Executed