Get week day of current time in specified time zone - javascript

I need to get the week day of the current time in a specified timezone, and without using libraries. Numbered week days or strings are both fine.
I've used this approach to switch timezone:
new Date().toLocaleString("en-US", {timeZone: "America/Chicago"})
but the output is a string so I can't do date logic in it.
PS: I am on Google Apps Script, which is why I mentioned no libraries.

you can use special options for that:
{ weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
to show a week day:
new Date().toLocaleString('en-US', {day: '2-digit', timeZone: 'America/Chicago' })
or to show full day name:
new Date().toLocaleString('en-US', {weekday: 'long', timeZone: 'America/Chicago' })

I am suggesting you use the Intl.DateTimeFormat
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: "America/Chicago",
weekday: 'long',
})
console.log(formatter.formatToParts(new Date()))
// you get an array like : [{type: "weekday", value: "Friday"}]

You can use the Moment for this. It gives weekdays from local.
moment.months()
moment.monthsShort()
moment.weekdays()
moment.weekdaysShort()
moment.weekdaysMin()
It is sometimes useful to get the list of months or weekdays in a locale, for example when populating a dropdown menu.
moment.months();
Returns the list of months in the current locale.
[ 'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December' ]
Similarly, moment.monthsShort returns abbreviated month names, and moment.weekdays, moment.weekdaysShort, moment.weekdaysMin return lists of weekdays.
You can pass an integer into each of those functions to get a specific month or weekday.
moment.weekdays(3); // 'Wednesday'
As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week, thus:
moment.locale('ar');
moment.weekdays(true); // lists weekdays Saturday-Friday in Arabic
moment.weekdays(true, 2); //will result in Monday in Arabic

Related

conversion of an object to UTC ISO time format

I have an object with time information.
const dateTime = {
day: 3,
hour: 18,
minute: 22,
month: 11,
second: 54,
timeZoneOffset: -60,
year: 2022
}
How do I convert this object to ISO UTC time format?
The Date API allows to build a date object with all your arguments.
You'd have to create a new Date object with your value, and then you can convert your object to the format you want (UTC ISO string...).
If the timezone is not the timezone of the locale machine, you'd have to workaround with the setTime method.
see
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Also see this answer for more info about setting time zone
const dateTime = {
day: 3,
hour: 18,
minute: 22,
month: 11,
second: 54,
timeZoneOffset: -60,
year: 2022
};
const {
day,
hour,
minute,
month,
second,
year,
timeZoneOffset
} = dateTime;
const d = new Date(Date.UTC(year, month, day, hour, minute, second));
d.setTime(d.getTime() + timeZoneOffset * 60000);
console.log(d.toISOString());
console.log(d.toUTCString());

Passing options argument to The toLocaleString() method removes the time portion from the output

I want to convert a UTC timestamp to mm/dd/yyyy hh:mm:ss format in Javascript.
timestamp = '1645199199.241098'
const d1 = new Date(parseInt(timestamp) * 1000)
.toLocaleString("en-US",
{
hour12:false,
timeZone: 'America/Chicago',
});
console.log(d1)
This code above does not give me two digit months and days. Setting the options for 2-digit month and day gives me the correct date format but removes the time from the output all together.
timestamp = '1645199199.241098'
const d2 = new Date(parseInt(timestamp) * 1000)
.toLocaleString("en-US",
{hour12:false,
timeZone: 'America/Chicago',
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
console.log(d2);
How do I retain the time and get the date in the desired format in my output?
When you start specifying what parts you want to have in the string, the rest of them default to being absent. If you want the time, you need to tell it that:
const timestamp = "1645199199.241098"
const d2 = new Date(parseInt(timestamp) * 1000)
.toLocaleString("en-US", {
hour12: false,
timeZone: "America/Chicago",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "numeric", // ***
minute: "numeric", // ***
second: "numeric", // ***
});
console.log(d2);
You can add the remaining options for hour, minute, and second:
const timestamp = '1645199199.241098';
const d2 = new Date(parseInt(timestamp) * 1000)
.toLocaleString("en-US", {
hour12: false,
timeZone: 'America/Chicago',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
console.log(d2);
Documentation regarding available options and value format values:
https://tc39.es/ecma402/#sec-datetimeformat-abstracts

toLocaleDateString() returns year with 2 digit instead of 4 in React-Native

When I call toLocaleDateString() I expected the year in 4 digits like 08/15/2021
new Date().toLocaleDateString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }) // 08/15/21
or
new Date().toLocaleDateString('en-Gb') // 08/15/21

Convert custom string into Angular Date

I have a string like "August 24th, 2020" that I need to convert into the "Date" type in Angular. Is there any simple way to do this please?
I've tried this:
const deadline = new Date ("August 24th, 2020")
But that results in "Invalid Date".
Maybe moment.js is capable to parse that outside of the box, however, if you're not willing to attach external library and maintain its compatibility to the rest of your environment for this purpose only, you may parse that yourself:
const dateStr = "August 24th, 2020",
parseDate = s => {
const [, month, dd, yyyy] = s.match(/([a-z]+)\s(\d+)[a-z]+,\s(\d+)/i)||[],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
return new Date(Date.UTC(yyyy, months.indexOf(month), dd))
}
console.log(parseDate(dateStr))

Control Month Year in Dropdown list

I am trying to control "Month" and "Year" in drop down list. I am having two fields, "Start Date" and "End Date". In that "Start Date" I am listing the "Current Month" and "Year" like "March 2020". I want to control my "End Date" based of "Start Date". For example if there is no "Month" selected in "Start Date" I should not allow user to select the "End Date". If user select's "MAY 2020" in "Start Date" and in "End Date" I want to display from "May 2020 to next May 2021". Like wise if user select's "June 2020" in "Start Date" and in "End Date" I want to display from "June 2020 to next June 2021". As of now I am displaying the current month and year in both Start and End date. Any one can guide me to achieve this. Thanks in Advance. Below is the code where I am getting current year month to next year.
const fareMon = () => {
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const currDate = new Date();
const year = currDate.getFullYear();
const months = [];
let currentMonthIndex = currDate.getMonth();
let yearsToAdd = 0;
for (let i = 0; i < 13; i += 1) {
if (currentMonthIndex === 12) {
currentMonthIndex = 0;
yearsToAdd += 1;
}
const futYear = year + yearsToAdd;
months.push(<option value={`${monthList[currentMonthIndex]} ${futYear}`}>{`${monthList[currentMonthIndex]} ${futYear}`}</option>);
currentMonthIndex += 1;
}
return <>{months}</>;
};
So, what I have done is, created a getFullYear function, where you can pass year and you will get all the months
Does this help:
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const getFullYear = (year) => {
const currentDate = new Date(`01 01 ${year}`);
const monthYear = [];
for(;currentDate.getFullYear() === year;){
const currentMonth = currentDate.getMonth();
monthYear.push(`${monthList[currentMonth]} ${year}`)
const nextMonth = currentMonth+1;
currentDate.setMonth(nextMonth);
}
return monthYear;
}
More cleaner and less compute intensive approach would be:
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const getYear = (year) => {
return monthList.map((month) => `${month} ${year}`);
}

Categories