Javascript date not properly converting to local time - javascript

I have a string called stringDate that is equal to 2023-01-20T04:48:42.327000 which is a string. This is in UTC time. I live in the Pacific timezone so the following code should return 2023-01-19T20:48:42.327Z but it's returning 2023-01-20T12:48:42.327Z. Why is this happening?
let date: any = new Date(stringDate);
console.log(date);

To force new Date() to parse a date time object as UTC you can append a zero time zone offset to it.
let date: any = new Date(stringDate + '+00:00');

The issue is most likely due to the fact that JavaScript's Date object assumes that the input string is in local time, not UTC. This means that the Date object is automatically converting the input string to the local time zone.
So using .toISOString() method, which will return a string in ISO format, including the UTC offset (represented by 'Z' at the end):
let date: any = new Date(stringDate);
console.log(date.toISOString());
This will correctly parse the input string as UTC time and output the expected result 2023-01-19T20:48:42.327Z.

Related

Converting a DateTime Object to a specific timezone

I have a dateTime string "2019-02-14 17:18:22".
I would like to convert this above-mentioned dateTime string to a specific timezone dateTime .
Here the timezone will be extracted from another dateTime string - "2019-02-14T17:28:24+08:00".
I did look up at the utcOffset function but I don't know how to use the offset value (330 in mycase).
Expected result: The first String is fairly simple 5:18 PM .
But once getting converted to the specific timezone, it will be 2:48 PM.
Heres how I use timezone offsets.
I get DateTimeIn, which is offset to (UTC+00:00) from the server.
Then to convert to the browser's timezone (UTC-05:00), i use: getTimezoneOffset() to update the object to the local timezone.
var dateObj = new Date(DateTimeIn);
dateObj.setMinutes(dateObj.getMinutes() + dateObj.getTimezoneOffset());
Without this, my server downloaded datetimes are offset and unusable.

Display ISO 8601 date string as local date and time based on navigator.language

I've been trying to display the local date and time after parsing ISO string to local timestamp based on navigator.language.
let sampleDate = new Date('2018-11-29T09:54:46.863207Z').toLocaleString(navigator.language);
So when I change the browser language preferences it reflects the date format in proper locale, but this doesn't seem to work with time part of the ISO string.
Result with browser locale en-AU--
Data Last Updated at 29/11/2018, 3:24:46 pm
Result with browser locale en-US -- Data Last Updated at 11/29/2018, 3:24:46 pm
See how only the date format changes based on the locale.It doesn't seem to affect the time component of the ISO 8601 string.
I've tried using moment.js to get the display the date and time in browser locale format but didn't find much success.
Am I missing something here?
It looks like you are trying to take a UTC date string, convert it to the client browser's local date and time, and format the date based on locale. You may be overthinking it a bit as JavaScript does most of this for you as long as you correctly create the Date object.
It is not recommended to parse date strings with the new Date() constructor, so the code example below uses a little regex and unpacking to parse the date string, then you can create the date in UTC with new Date(Date.UTC(...)). At that point, JavaScript will represent the date object in the client browser's local date and time automatically, then you can use toLocaleString() to apply formatting for the client browser's locale. For example:
const s = '2018-11-29T09:54:46.863207Z';
const [y, m, d, hh, mm, ss, ms] = s.match(/\d+/g);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
const formatted = date.toLocaleString();
console.log(formatted);
If you need the Date for a particular time zone:
date.toLocaleDateString('en-AU', {timeZone: 'Australia/Sydney'})
date.toLocaleDateString('en-US', {timeZone: 'America/New_York'})
You can try this
console.log(
(new Date).toLocaleString('en-AU', {timeZone: 'Australia/Sydney'}) + "\n" +
(new Date).toLocaleString('en-US', {timeZone: 'America/New_York'})
)
18/10/2021, 10:05:25 pm
10/18/2021, 7:05:25 AM

JavaScript date object from <input type=date>

I'm trying to create a javascript date object in the focus.add_days function to add some days to the given date in a element.
the problem is that the javascript object doesn't expect a string "Y-m-d" so how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?
trigger = {
fecha_ini: function(){
$('input[name="fecha_ini"]').on('change',function(){
console.log('hi');
var fecha_fin = $(':input [name=fecha_fin]');
var min = $(this).val();
//here is where i pass the "Y-m-d" string as the date argument
var max = fechas.add_days(min,31*4);
fecha_fin.attr('min',min);
fecha_fin.attr('max',max);
fecha_fin.val('');
})
}
};
fechas = {
add_days: function addDays(date, days) {
//here is where i use the string "Y-m-d" to create the date object, but obviusly doesnt work
var result = new Date(date);
result.setDate(date.getDate() + days);
return result;
}
};
trigger.fecha_ini();
Use valueAsDate:
valueAsDate
Returns: Date
Returns / Sets the value of the element, interpreted as a date, or null if conversion is not possible.
Demo:
<input type="date" id="d" value="2018-02-14">
<button onclick="console.log( document.getElementById('d').valueAsDate )">
change the date (or not) and click me
</button>
how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?
While Date.parse will convert strings in y/m/d/ format to date objects, manual parsing is the only sensible way:
// s is format y-m-d
// Returns a date object for 00:00:00 local time
// on the specified date
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
ES5 specifies a form of ISO 8601 that should be supported by all browsers, however it is not supported consistently or by all browsers in use.
UTC
javascript Date object parses the raw value of <input type=date> in the UTC time zone, always!
new Date(input.value) // Date object, date interpreted as UTC but printed in the local TZ
Date.parse(input.value) // Unix time in ms, date interpreted as UTC
Local Time Zone
If the value of the <input type=date> is meant to be interpreted in the local timezone, then you can force it by adding a time like this:
new Date(input.value+"T00:00") // Date object, date interpreted and printed in the local TZ
Date.parse(input.value+"T00:00") // Unix time in ms, date interpreted as local TZ
Why?
emphasis mine
For example, "2011-10-10" (date-only form), "2011-10-10T14:48:00" (date-time form), or "2011-10-10T14:48:00.000+09:00" (date-time form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Description
With me it's working without doing anything.
I just write
new Date($('#html5dateinput').val());
that's about it. I get the correct date object. I'm using Google Chrome ver 38 and I tested it on Firefox 33 under Ubuntu 14.04
Use valueAsNumber.
var myDate = new Date(input.valueAsNumber);

Changing timezone when conver to JSON

I want to take date in my module with JSON format and when I am converting my date value to json then it changes the timezone ultimately date gets change for eg
var myDateWithJson=(new Date(2014, 03, 11).toJSON());
alert("Date With Json " +myDateWithJson);
var myDateWithoutJson = new Date(2014,03,11);
alert("Date Without Json " + myDateWithoutJson);
I also gone through covert json without timezone but, I don't think that is better approch
Please guide me for the better approch
In your code:
var myDateWithJson=(new Date(2014, 03, 11).toJSON());
will create a date object for 00:00:00 on the morning of 11 April 2014 (note that months are zero indexed here) in your current locale based on system settings. Calling toJSON returns an ISO 8601 date and time string for the equivalent moment based on UTC.
The date object will have an internal time value that is milliseconds since 1970-01-01T00:00:00Z.
var myDateWithoutJson = new Date(2014,03,11);
That creates a date object for exactly the same moment in time, i.e. with exactly the same time value.
alert("Date Without Json " + myDateWithoutJson);
That calls the toString method of the date object that returns a human readable string representing the date and time in the current locale based on system settings.
So the first is a UTC string, the second is a local string. Both represent the exact same instant in time, and, if converted back to Date objects, will have exactly the same internal time value.

Convert date time in utc

i have to convert date in utc from locale date time in birt.
The only problem is that the date is divide in two numeric data type like '20131012' instead for 'yyyyMMdd' and '223112'instead for 'h24:mi:ss'.
Can anyone help to convert this two data type affected from locale settings, with other two in UTC mode?
thanks for anyone just read this..
Javascript Date objects are based on a UTC time value. When methods such as date.toString are called, the local system settings are used to show a local date and time.
You can use Date.UTC to create a UTC time value, use that to create a date object, then use the date object to get a local (system) equivalent date and time.
e.g.:
var utcDate = '20131012';
var utcTime = '223112';
// Get a UTC time value
var timeValue = Date.UTC(utcDate.substring(0,4),
utcDate.substring(4,6) - 1, // Months are zero indexed
utcDate.substring(6),
utcTime.substring(0,2),
utcTime.substring(2,4),
utcTime.substring(4)
);
// Convert time value to date object
var date = new Date(timeValue);

Categories

Resources