Convert the local time to another time zone with this JavaScript - javascript

I need to increase the current date in Moscow time by 1 day every time the clock is 15:00 and more. I did it at local time, but I can’t do it according to Moscow time (UTC + 3)
function date() {
const today = new Date();
const t = today.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (t >= 15) {
today.setDate(today.getDate() + 1);
document.querySelector('.date').innerHTML = dtfRU.format(today);
} else document.querySelector('.date').innerHTML = dtfRU.format(today);
}
document.addEventListener("DOMContentLoaded", date);

I found a solution here: enter link description here I needed to do something like this:
function calcTime() {
const now = new Date();
const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
const d = new Date(utc + (3600000 * 3));
const h = d.getHours();
const dtfRU = new Intl.DateTimeFormat('ru', {
month: 'long', day: '2-digit',
});
if (h >= 15) {
const newd = new Date(utc + (3600000 * 3 * 9));
document.querySelector('.date').innerHTML = dtfRU.format(newd);
} else document.querySelector('.date').innerHTML = dtfRU.format(d);
}
document.addEventListener("DOMContentLoaded", calcTime);

You can retrieve the local hour in Moscow as follows:
// Get a DateTimeFormat object for the hour in Moscow in 24-hour format
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false
});
// The above will create a format that has only the hour, so you can just use it.
const hour = +dtf.format();
console.log("hour:", hour);
Alternatively, if you decide you need more than just the hour, use formatToParts. For example:
const dtf = Intl.DateTimeFormat('en', {
timeZone: 'Europe/Moscow',
hour: 'numeric',
hour12: false,
minute: 'numeric'
});
const parts = dtf.formatToParts();
const hour = +parts.find(x => x.type === 'hour').value;
const minute = +parts.find(x => x.type === 'minute').value;
console.log("hour:", hour);
console.log("minute:", minute);
You can then use that in the rest of your code however you wish.

Related

Get weekday list between two dates? JavaScript

How to get weekday list between two dates? I need javaScript function for that. (date-fns library function also is Ok)
as e example
getWeekDayList('2022-01-10', '2022-01-20');
function getWeekDayList(startDate, endDate){
//Output should be week days only
2022-01-10
2022-01-11
2022-01-12
2022-01-13
2022-01-14
2022-01-17
2022-01-18
2022-01-19
2022-01-20
}
You can use a for loop to loop through each date between the start and end date, then use Date.getDay to get the day of the week and ignore the dates that are not a weekday.
function getWeekDayList(startDate, endDate) {
let days = []
let end = new Date(endDate)
for (let start = new Date(startDate); start <= end; start.setDate(start.getDate() + 1)) {
let day = start.getDay();
if (day != 6 && day != 0) {
days.push(new Date(start));
}
}
return days;
}
const result = getWeekDayList('2022-01-10', '2022-01-20')
console.log(result.map(e => e.toLocaleString('en-US', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })))

Format Date to MM/DD/YYYY Using toLocaleString

In JS, how can I get the date to format to MM/DD/YYYY?
new Date(Date.now() + (8 * 86400000)).toLocaleString().split(',')[0])
returns "12/1/2020"
How can I format it to "12/01/2020"?
fromDate:
(new Date(Date.now() + (1 * 86400000)).toLocaleString().split(',')[0]),
toDate:
(newDate(Date.now() + (8 * 86400000)).toLocaleString().split(',')[0])
I would like the fromDate and toDate to be:
If between 5:00 PM MST and Midnight: set fromDate to tomorrow's date , and toDate to tomorrow's date + 7 days
How can compare the currentTime to say if it is greater than 5 PM local time?
let currentTime = new Date().toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
You can use the options argument in .toLocaleString to format your date as "MM/DD/YYYY"
var currentDate = new Date(Date.now() + (8 * 86400000))
var newDateOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit"
}
var newDate = currentDate.toLocaleString("en-US", newDateOptions );
console.log(newDate)
A detailed post on how to use the arguments in .toLocaleString - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
This from another post here.
var currentD = new Date();
var startHappyHourD = new Date();
startHappyHourD.setHours(17,30,0); // 5.30 pm
var endHappyHourD = new Date();
endHappyHourD.setHours(18,30,0); // 6.30 pm
console.log("happy hour?")
if(currentD >= startHappyHourD && currentD < endHappyHourD ){
console.log("yes!");
}else{
console.log("no, sorry! between 5.30pm and 6.30pm");
}

Date script doesn't work correctly when is Saturday [duplicate]

The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');

javascript convert dates format [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I am facing an issue in javascript dates. I want to display previous and after 30min
How should I added previous or after 30min in current dates.
this.setState({
current: new Date().toLocaleTimeString(), //10:30:02 PM
slotTime: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}), //10:30 AM
Output:
10:30 AM //current date
expected:
10:00 AM //previous
10:30 AM //current
11:00 AM //after 30min
anyone help me?
You can simply do it like this:
var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes
var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);
console.log("Current time: ", new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) //current time
console.log("Reduced time: ", reductedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // reduced time by 30mins
console.log("Added time: ", addedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // added time by 30mins
Hope this help
/* required:
* - timestamp => number of timestamp format
* - format => return format, ex. format 1 (23:59:59), format 2 (23:59)
* return: time with string
*/
function timestampToTime(timestamp, format = 1) {
if (!isNaN(timestamp) || timestamp != undefined) {
let dd = new Date(timestamp)
if (format == 1) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2) + ':' + ('00' + dd.getSeconds()).slice(-2)
} else if (format == 2) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2)
}
} else {
return null
}
}
let dd = + new Date()
let previous = timestampToTime(dd - (1.8e+6)) // 1.8e+6 = 30 min
let current = timestampToTime(dd)
let after = timestampToTime(dd + (1.8e+6)) // 1.8e+6 = 30 min
console.log(previous)
console.log(current)
console.log(after)

Moment.js diff of two moments defined by week and weekday gives wrong result

I want to calculate the difference between a moment (itemMoment) and now (nowMoment) defined by weekday, hour and minute. If the itemMoment is before nowMoment (diff < 0) I want to add one week and calculate the difference again, but the addition of a week (week: week + 1 in my code )somehow doesn't change the difference and I still get a negative difference.
It's the first time I use the moment.js library so may be I don't get it how to use it correctly. Would be great if an experienced used could help.
var now = moment();
var year = now.year();
var week = now.week();
var weekday = now.weekday();
var hour = now.hour();
var minute = now.minute();
var itemMoment = moment({
day: item.weekday,
hour: item.hour,
minute: item.minute
});
var nowMoment = moment({
day: weekday,
hour: hour,
minute: minute
});
if (itemMoment.diff(nowMoment) > 0) {
item.date = moment({
year: year,
week: week,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = itemMoment.diff(nowMoment);
}
else {
if (week == 51) {
week = -1;
year = year + 1
}
item.date = moment({
year: year,
week: week + 1,
weekday: item.weekday,
hour: item.hour,
minute: item.minute
});
diff = item.date.diff(now);
you can just do comparison using isBefore() or isAfter(). http://momentjs.com/docs/#/query/
if (itemMoment.isBefore(nowMoment)) {
Then you can do manipulation like so: http://momentjs.com/docs/#/manipulating/
item.date = itemMoment.add('weeks', 1);

Categories

Resources