Get Timezone Abbreviation from String - javascript

How would I get the time and abbreviated timezone from a String. What I am doing incorrectly?
const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const timezoneAbbreviation = moment.tz(timestampString).format('z'); // expecting PST, but result is UTC

That functionality was deprecated in moment and only available via moment-timezone like this:
const timestampString = 'Wed Dec 05 2018 22:00:00 GMT-0800 (Pacific Standard Time)';
const result = moment(new Date(timestampString)).tz('America/Los_Angeles').format('z')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
Note: that you need to instantiate moment with valid date first etc.
The reasoning behind this is that there was no consistent way to get that time zone abbreviation just from the native Date object toString as you can read here.

For anyone who is using date-fns-tz, you can find timezone abbreviation as following
const { utcToZonedTime, format } = require('date-fns-tz')
const date = new Date('2018-09-01T16:01:36.386Z')
const zonedDate = utcToZonedTime(date, 'America/Toronto')
const pattern = 'zzz'
const timeZoneAbbr = format(zonedDate, pattern, { timeZone: 'America/Toronto' })
-> timeZoneAbbr : EDT
Above is an example given in the documentation page

Related

DayJS: Format and Convert an ISO Date/Time String to Local Timezone's Date/Time

I'm consuming an API which returns timestamps in this format 2023-02-18T14:54:28.555Z which is an ISO string. I need to format this value to the timezone of the user.
I've tried this:
dayjs("2023-02-18T14:54:28.555Z").format('YYYY-MM-DD HH:MM:ss A') // => "2023-02-18 20:02:28 PM"
The above output is incorrect and is 30 minutes behind for +0530 IST Timezone.
But when I input the same string "2023-02-18T14:54:28.555Z" to the JavaScript date constructor, I can see the correct value.
new Date("2023-02-18T14:54:28.555Z").toString() // => 'Sat Feb 18 2023 20:24:28 GMT+0530 (India Standard Time)'
How to get the correct formatted value for my Timezone using DayJS?
Tried feeding the ISO string to the DayJS constructor and expected it'll parse it to the current timezone. But the output value is 30 minutes behind.
you can use toLocaleString() method:
const timestamp = "2023-02-18T14:54:28.555Z";
const date = new Date(timestamp);
const options = { timeZone: 'Asia/Kolkata' };
const formattedDate = date.toLocaleString('en-US', options);
console.log(formattedDate);
Date.toString() displays the Date according to the local time of the OS. If you need the time to display in a zone other than the local time of the OS, then you'll have to use the DayJS Timezone plugin.
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
const timestamp = '2023-02-18T14:54:28.555Z';
dayjs.extend(utc);
dayjs.extend(timezone);
// Seattle time because my OS is set to America/Los_Angeles time.
const seattleString = Date(timestamp).toString();
const dayjsLocal = dayjs(timestamp);
const dayjsIst = dayjsLocal.tz('Asia/Calcutta');
const istString = dayjsIst.format('YYYY-MM-DDTHH:mm:ss');
console.log(seattleString); // Sun Feb 19 2023 02:43:42 GMT-0800 (Pacific Standard Time)
console.log(istString); // 2023-02-18T20:24:28

The wrong date format in Javascript

I am using luxon library to convert the time:
const DateTime = luxon.DateTime;
console.log(DateTime.local('Sun Jan 23 2003 00:00:00 GMT+0200 (Eastern European Standard Time)').toISODate())
<script src="https://cdn.jsdelivr.net/npm/luxon#2.3.1/build/global/luxon.min.js"></script>
I expect to get this format: 2003-04-23 Why i get null and how to get the expected format using luxon?
You have the date format wrong, Luxon’s format that belongs in .local is year?, month, day, hour, minute, second, millisecond
Example:
const DateTime = luxon.DateTime;
console.log(
DateTime.local(2003, 1, 23, 17, 36) .toISODate())
<script src="https://cdn.jsdelivr.net/npm/luxon#2.3.1/build/global/luxon.min.js"></script>
For your case you can use the code below to get what you are looking for.
const DateTime = luxon.DateTime;
const date = new Date("Sun Jan 23 2003 00:00:00 GMT+0200 (Eastern European Standard Time)")
const dat = DateTime.fromJSDate(date)
console.log(dat.toFormat('MM-dd-yyyy'))
<script src="https://cdn.jsdelivr.net/npm/luxon#2.3.1/build/global/luxon.min.js"></script>
can be done with pure date
var date =new Date("Sun Jan 23 2003 00:00:00 GMT+0200 (Eastern European Standard Time)")
const DateTime = luxon.DateTime;
var dat = DateTime.fromJSDate(date)
console.log(dat.toString().split("T")[0])
<script src="https://cdn.jsdelivr.net/npm/luxon#2.3.1/build/global/luxon.min.js"></script>

How to change ISO date to Standard JS Date?

I am trying to change an ISO date to a Standard JS Date format. The JS format I am referring to is:
Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)`
What is the best way to go about doing this? Thanks!
const ISO_DATE = '2020-07-14T23:02:27.713Z';
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toString();
};
console.log(formatDate(ISO_DATE));
One way is:
let isoDate = "2020-07-20T14:29:52Z";
var myDate = new Date(isoDate);
console.log(myDate.toString()); // Mon Jul 20 2020 17:29:52 GMT+0300 ( (your time zone)
console.log("Back to ISO Date: ", myDate .toISOString());
If you want to convert it back to ISO Date use:
console.log(myDate.toISOString());

Convert date string into another string format

I have the date in this format:
Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
I want this string to be converted into this format:
2016-11-15 00:00:00
I tried:
var s = startDate.format('YYYY-MM-DD HH:mm:ss');
I would recommend using the library moment.js. This library was specifically designed to help with dates and formatting.
You simply need to do this:
let date = moment('Tue Nov 15 2016 00:00:00 GMT+0800').format('YYYY-MM-DD HH:mm:ss')
console.log(date)
However, there is a caveat. Since the date that you are providing is in a nonstandard format, you will get a deprecation warning, like this:
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Basically, the solution is to provide a standard format for your date. The simplest way to do that is to either chop off the timezone, since it seems like you will be displaying the date assuming the TZ supplied is the local one.
You can get it done just using vanilla javascript:
const date = new Date('Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time');
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeToHHMMSS = (hours, minutes, seconds) => {
return [hours, minutes, seconds].map(value => {
return ('0' + value).slice(-2);
}).join(':');
}
const formattedDate = `${year}-${month}-${day}`;
const formattedTime = timeToHHMMSS(hours, minutes, seconds);
console.log(`${formattedDate} ${formattedTime}`);

Get exact day from date string in Javascript

I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?
Also I have looked into http://home.clara.net/shotover/datetest.htm
My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)
And I want to convert it to dd-mm-yyyy format.
I tried using:
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
But it gives me the result as: 1-6-2013
The getDay() value is the index of day in a week.
For Instance,
If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013
How can I get the proper value of Day?
P.S: I tried using .toLocaleString() and creating new date object from it. But it gives the same result.
To get the day of the month use getDate():
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
W3 schools suggests just building your days of the week array and using it:
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[d.getDay()];
Not super elegant, but usable.
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
Replace getDay() with getDate().
The above will return the local date for each date part, use the UTC variants if you need the universal time.
I think you will have to take an Array of the days & utilize it using the received index from the getDay() method.
To get required format with given date will achieve with moment.js.
a one liner solution is
import moment from "moment";
const date = new Date();
const finalDate = moment(date).format("DD-MM-YYYY")

Categories

Resources