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 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.
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 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.
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() );
convert string to date without changing timezone in the string using java
Just omit the timezone format from the end of the String (letter Z
).
For example, this will print Thu Nov 12 06:30:00 CET 2020
String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
var date = format.parse(s);
System.out.println(date);
But if I add the letter Z
at the end, it will interpret the given timezone and change time to my local timezone, when printed. So this will print Thu Nov 12 15:30:00 CET 2020
String s = "2020-11-12T6:30:00-0800";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
var date = format.parse(s);
System.out.println(date);
More about the patterns can be found in the JavaDoc of SimpleDateFormat.
Javascript, Date.parse with no timezone
Date.parse
returns the number of milliseconds since the epoch in UTC, so no matter what date/time string you pass in, you'll get UTC out. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse for more information.)
If you want to convert that to local time, you'll have to know your offset from UTC. You can get that from JavaScript thusly:
var offset = new Date().getTimezoneOffset()*60*1000;
(Date.prototype.getTimezoneOffset
returns the offset in minutes, so we have to convert to milliseconds.)
Then you can construct your date with that offset:
var date = new Date(Date.parse("2014-06-01T00:00:00") + offset);
If you want to interpret that date as if it were in a different timezone, you would just use whatever millisecond offset is appropriate for that timezone. Keep in mind daylight savings, though: that will definitely complicate matters.
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.
Related Topics
How to Get a Word Under Cursor Using JavaScript
Accessing Redux State in an Action Creator
Expression Inside Switch Case Statement
How to Use JavaScript to Read Local Text File and Read Line by Line
Trigger CSS Animations in JavaScript
Maximum Item Size in Indexeddb
Programmatically Play Video with Sound on Safari and Mobile Chrome
Search and Highlight in Jquery
Using Settimeout on Promise Chain
Web Workers Without a Separate JavaScript File
Filter Array of Objects with Another Array of Objects
How to Get All Selected Values from <Select Multiple=Multiple>
Can Someone Explain This 'Double Negative' Trick