Convert hour UTC time to local time moment.js - momentjs

I wanted to convert "1" being UTC time to local time like this:
const selectedHour = "1";
const result = moment(selectedHour, "hh").local().format('hh');
But I get "1" itself;
Need your help

You should treat 1 as UTC. In order to do this, moment has a constructor which treats input as UTC date.
Be careful about formats. h represents 12 hour time without leading zero, hh with leading zero. HH is for 24 hour time. Check https://momentjs.com/docs/#/parsing/string-format/
const selectedHour = "1";
const result = moment.utc(selectedHour, "h").local().format('hh');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related

Subtract number of hours from current time in Java

I have a string that represents time duration of 54:34:41 i.e. 54 hours, 34 minutes, 41 seconds.
I would like to extract the 54 hours and subtract it from the current system time.
However when I run below I get java.time.format.DateTimeParseException: Text '54:34:41' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 54
How can I extract 54 hours and subtract from current time?
private val formatterForTime: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss")
val timeDuration = formatterForTime.parse("54:34:41")
val currentTime = LocalDateTime.now()
val newTime = currentTime.minusHours(timeDuration.get(ChronoField.HOUR_OF_DAY).toLong())
tl;dr
ZonedDateTime
.now(
ZoneId.of( "Asia/Tokyo" )
)
.minusHours(
Integer.parseInt( "54:34:41".split( ":" )[0] )
)
Details
Parse hours
Get the number of hours.
int hours = Integer.parseInt( "54:34:41".split( ":" )[0] ) ;
ISO 8601
Your input text for a span-of-time does not comply with the ISO 8601 standard for date-time values. The java.time classes by default use the standard formats when parsing/generating text.
If instead of 54:34:41 you had PT54H34M41S, then we could use:
int hours = Duration.parse( "PT54H34M41S" ).toHours() ;
I recommend you stick with the standard format rather than the ambiguous clock-time format.
Capture current moment
Capture the current moment as seen in a particular time zone.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Subtract hours
Subtract your hours.
ZonedDateTime earlier = zdt.minusHours( hours ) )

How to create an event series with a start date and an end date

First of all, sorry if my English isn't good as I'm a french guy.
I have a problem with a google script I took on the internet that automatically inputs holliday in my calendar.
Let me explain in detail: I use a google form to get all the data I need to input my calendar, such as the name of the employee, the start date of his holliday, the end date, and other information like mail and stuff. The start date and end date are with hours to indicate at which hour start and finish the holliday.
Here's my problem, I use CreateEventSeries but when I use this, it creates a "bar" until the end date but I would like to have an event day by day, until the end date, that finish at 18pm.
Here's the code i use :
else if (approval == Approval.Approved && reason == Reason.Vacation) {
CalendarApp.getCalendarById(email)
.createEventSeries(
'CP',
startDate,
endDate,
CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.THURSDAY, CalendarApp.Weekday.FRIDAY])
.until(endDate),
{
description: message,
sendInvites: true,
}
);
// Send a confirmation email.
let subject = 'Congés acceptés';
MailApp.sendEmail(additionalEmail, subject, message, );
row[Header.NotifiedStatus] = NotifiedStatus.Notified;
Logger.log(`Approved, calendar event created, row=${JSON.stringify(row)}`);
}
I don't know if I made myself clear.
I don't want an all-day event cause it's not visible enough on the calendar.
In short, I would like to create an event series day by day from 8 am until 18pm with a start date and an end date.
Does someone have a solution or a lead?
Best regards
Issue:
When creating an event series via createEventSeries(title, startTime, endTime, recurrence, options), the parameters startTime and endTime refer to the start and end time of the first event in the series, not of the series as a whole:
startTime: the date and time when the first event in the series starts
endTime: the date and time when the first event in the series ends
This endTime is completely different from what you want to set at until(endDate), which refers to when the series of events will finish.
Code snippet:
For example, if you want to have an event every day that lasts from 8 AM to 6 PM, from, let's say, 1 to 15 May, you would do this:
const startTime = new Date('May 1, 2021 08:00:00 GMT+01:00');
const endTime = new Date('May 1, 2021 18:00:00 GMT+01:00');
const endDate = new Date('May 15, 2021 18:00:00 GMT+01:00');
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
Update:
Assuming you have installed an onFormSubmit trigger, your function could be something like this:
function createEventSeriesOnSubmit(e) {
const formResponse = e.response;
let itemResponses = formResponse.getItemResponses();
const itemNames = ["startDate", "endDate", "startHour", "endHour"];
const responses = itemNames.map(itemName => getResponseForItem(itemResponses, itemName));
const [startDay, endDay, startHour, endHour] = responses;
const startTime = new Date(`${startDay} ${startHour}`);
const endTime = new Date(`${startDay} ${endHour}`);
const endDate = new Date(`${endDay} ${endHour}`);
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
}
Where "startDate", "endDate", "startHour", "endHour" are the names of the corresponding items in your Form. For example:
As you can see in the code sample, you can build the corresponding date to use in calendar by interpolating the date response and the time response, like this:
const startTime = new Date(`${startDay} ${startHour}`);
The resulting calendar has the series of events corresponding to the start hour, end hour, start date and end date that have been specified:

moment.js Timezone Parsing and Comparison

I'm receiving timestamps in the following format '2016-08-17T14:00:00-04:00', which I can parse in moment with moment('2016-08-17T14:00:00-04:00', 'YYYY-MM-DDTHH:mm:ssZ').
But the problem is that I want to print out .format('LLLL') and have it read Wednesday, August 17, 2016 10:00 AM, i.e. subtracting -04:00 from 14:00:00 (NY from UTC). It appears that there is a _tzm: -240 property in the moment object that looks like it holds that -4 hours value, but how do I use that property?
The other goal is to be able to pass in the current time and test if it is between the startDate and endDate variables below. I am guessing if I can convert both to NY-EST I can do this, but I can't seem to get moment to accept the timezone parameter.
Any thoughts?
var moment = require('moment');
// Timestamp strings from API
var startDate = '2016-08-17T14:00:00-04:00';
var endDate = '2016-08-17T15:00:00-04:00';
// Create a range from the start and end dates
var range = moment().range(new Date(startDate), new Date(endDate));
// Get the current time
var currentTime = new Date();
// Does the current time fall within the range b/w the start and end dates
range.contains(currentTime);
A solution I found is below. Adding the value from momentObj._tzm to the parsed date.
module.exports.convertDateToProperTimezone = function (dt) {
var _m = moment(dt, 'YYYY-MM-DDTHH:mm:ssZ');
return _m.add(_m._tzm, 'minutes');
};

Convert fulltime to minutes C#

I need convert GMT time 14:21:34 to minute (14*60+21=861 minutes)
I know there is a inbuilt function which convert min to HH:MM
Use TimeSpan.FromMinutes:
var result = TimeSpan.FromMinutes(1815);
Is there an easy way to do this that I am missing?
Two options to get to a TimeSpan:
1) Parse it as a DateTime (specifying a format), then use DateTime.TimeOfDay to get a TimeSpan
var dt = DateTime.ParseExact(
"14:21:34",
#"HH\:mm\:ss",
CultureInfo.InvariantCulture);
var ts = dt.TimeOfDay;
I like this option as it sounds like the value you've got is meant to be a time of day.
2) Parse it as a TimeSpan:
var ts = TimeSpan.ParseExact(
"14:21:34",
#"hh\:mm\:ss",
CultureInfo.InvariantCulture);
Once you have a TimeSpan, use TotalMinutes (which returns a double) to get the number of minutes. For example:
Console.WriteLine((int) ts.TotalMinutes); // 861

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

Resources