Convert date time in utc - javascript

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);

Related

Javascript date not properly converting to local time

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.

Display an Exact Date in JavaScript Regardless of TimeZone

I'm writing some simple code to display birthdays of some friends. I've got the birthdays stored in a JSON file and I'm pulling them in and initializing them as Date objects like so:
birthday: new Date(p.birthday)
Then I display those dates using moment to format them, like so:
let formatted = moment(birthdayDate).format(BirthdayFormat);
This applies an automatic local time zone, probably from when I set up the initial date object, and depending on the time of day might put the date a few hours in the past, thus changing the date to the previous day since it defaults to midnight.
Basically, I just want to display that date unchanging at any time since it's just stating that person's birthday and time zones aren't relevant at all. I use it elsewhere as a Date so I don't really want to store it in the JSON as formatted, so how can I set this up such that it just acknowledges the date and doesn't adjust it for a time zone?
From your comment, the dates are in YYYY-MM-DD format. Unfortunately, ECMAScript parses such dates as UTC.
If the date has already been parsed as UTC, then you just need to display UTC values to your users. You can use momentjs's utc function (I guess this is one of its main uses):
// Built-in parser treats YYYY-MM-DD as UTC
let d = new Date('2020-12-30');
// m inherits the same time value, so is also "UTC"
let m = moment(d);
// Include hour H in format to show effect of utc setting later
let birthdayFormat = 'dddd, D MMMM, YYYY [at] H';
// Default is local timezone, H reflects local offset
// Date might be 29 or 30, depends on whether offset is - or + respectively
console.log('Local: ' + m.format(birthdayFormat));
// Toggle UTC switch, all output will now be UTC, not local
m.utc();
// Values are now UTC, so offset is zero and so is H
// Displays Wednesday, 30 December, 2020 at 0 for all users
console.log('UTC : ' + m.format(birthdayFormat));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Convert the date to the date string so that the date does not include the timezone specific value.
birthday: new Date(p.birthday).toDateString()
Then display with the momentjs
let formatted = moment(birthdayDate).format(BirthdayFormat);

How to add time zone to specific format in momentjs?

I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.

Angular 6 Typescript new Date is created in UTC, but I need in my local timezone

In my file HomeComponent.ts (not in template html). I create a new Date and show it in console like this:
var fecha = new Date();
console.log(fecha);
the time in my country now is 16:09 (UTC -3) but the console output shows the date in UTC:
Date 2018-12-20T19:09:32.910Z // the time is 19:09
I need to compare and do some operations with "this new date" and other dates saved in a DB so I need the new Date to be created in my local timezone. How can I create a new Date in my local timezone?
How can I create a new Date in my local timezone?
Dates don't have a timezone, they are simply an offset from 1970-01-01T00:00:00Z (a time value) so are effectively always UTC. They represent a particular moment in time and can be used to generate a string representing an equivalent date and time in any timezone.
The local offset comes from the host system, it's used (if necessary) when creating a date and when working with local date and time values. There are equivalent UTC methods for doing operations that don't consider the local timezone.
The default toString method will generate a timestamp for the host timezone, toISOString will use UTC, toLocaleString can be used to generate a timestamp for any timezone. All will represent the same UTC date and time, just in different timezones.
When comparing dates, it's the UTC time value that is compared as it provides a common factor for all dates.
the time in my country now is 16:09 (utc -3) but the console output show the date in utc
A Date or DateTime is a structure, it does not have a format. If you want to display a formatted date string using the timezone of the browser then call toLocaleString.
var fecha = new Date();
console.log("As ISO8601 in utc:", fecha);
console.log("As local:", fecha.toLocaleString());

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.

Categories

Resources