Related
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>
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:
How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday
You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:
void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
UPDATE
Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)
Dart DateTimes have a weekday getter which is 1 for Monday and 7 for Sunday. Using that, I would do:
DateTime mostRecentSunday(DateTime date) =>
DateTime(date.year, date.month, date.day - date.weekday % 7);
to get the most recent Sunday (which is the start of the current week if the week starts on a Sunday), and
DateTime mostRecentMonday(DateTime date) =>
DateTime(date.year, date.month, date.day - (date.weekday - 1));
for the most recent Monday (which is then the start of the current week if the week starts on a Monday).
You can generalize to
/// The [weekday] may be 0 for Sunday, 1 for Monday, etc. up to 7 for Sunday.
DateTime mostRecentWeekday(DateTime date, int weekday) =>
DateTime(date.year, date.month, date.day - (date.weekday - weekday) % 7);
If you are going to be using the results as calendar dates, I'd used DateTime.utc as the constructor instead. (Always use UTC for calendar dates, then you can do day-based arithmetic on them safely).
I'd even consider using DateTime.utc in any case because it avoids any potential issues with a daylight saving that starts at midnight (rare, but with time zones, even unlikely things tend to have happened somewhere at some point).
The way you do this will probably depend on what your app's localization is. If you want to treat Sunday as the start of the week, you would do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay));
If you are treating Monday as the start, then do this:
DateTime now = DateTime.now();
int currentDay = now.weekday;
DateTime firstDayOfWeek = now.subtract(Duration(days: currentDay - 1));
MaterialLocalizations
If you're using Dart in Flutter, you can use the MaterialLocalizations class to get the index of the first day of the week (0 = Sunday, 6 = Saturday). This should help you decide which method from above that you should use.
The example given for the firstDayOfWeekIndex property is a good reference:
var localizations = MaterialLocalizations.of(context);
// The name of the first day of week for the current locale.
var firstDayOfWeek = localizations.narrowWeekdays[localizations.firstDayOfWeekIndex];
The MaterialLocalizations class comes with a ton of built in methods to format and display DateTimes.
dateTime: 2021-01-26 11:21:05.429320
formatFullDate: Tuesday, January 26, 2021
formatCompactDate: 01/26/2021
formatMediumDate: Tue, Jan 26
formatShortDate: Jan 26, 2021
formatShortMonthDay: Jan 26
formatMonthYear: January 2021
formatYear: 2021
If none of these fit your needs, you can also use the DateFormat class to specify how the DateTime should be displayed. It's important to note that the DateFormat class indexes days differently where 1 = Monday and 7 = Sunday.
DateFormat.yMMMd().format(new DateTime.now()) // Jan 26, 2021
DateFormat(DateFormat.ABBR_MONTH_DAY).format(now) // Jan 26
DateFormat(DateFormat.WEEKDAY).format(now) // Tuesday
FIRST DAY OF THE WEEK
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
LAST DAY OF THE WEEK
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime
.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
LAST DAY OF THE MONTH
DateTime findLastDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month + 1, 0);
}
FIRST DAY OF THE MONTH
DateTime findFirstDateOfTheMonth(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month, 1);
}
LAST DAY OF THE YEAR
DateTime findLastDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 12, 31);
}
FIRST DAY OF THE YEAR
DateTime findFirstDateOfTheYear(DateTime dateTime) {
return DateTime(dateTime.year, 1, 1); }
Dart/Flutter – How to find the first date and the last date of a week
1. Find the first date of the week
/// Find the first date of the week which contains the provided date.
DateTime findFirstDateOfTheWeek(DateTime dateTime) {
return dateTime.subtract(Duration(days: dateTime.weekday - 1));
}
2. Find the last date of the week
/// Find last date of the week which contains provided date.
DateTime findLastDateOfTheWeek(DateTime dateTime) {
return dateTime.add(Duration(days: DateTime.daysPerWeek - dateTime.weekday));
}
Testing
void main() {
// Find first date and last date of THIS WEEK
DateTime today = DateTime.now();
print(findFirstDateOfTheWeek(today));
print(findLastDateOfTheWeek(today));
// Find first date and last date of any provided date
DateTime date = DateTime.parse('2020-11-24');
print(findFirstDateOfTheWeek(date));
print(findLastDateOfTheWeek(date));
}
// Output
2020-11-23 06:54:42.865446
2020-11-29 06:54:42.865446
2020-11-23 00:00:00.000
2020-11-29 00:00:00.000
None of the above worked for me but #JoeMuller gave an interesting piece of info on the material localizations, which led me to find out that for what i want, sunday in date.weekday should be 0 took a while to figure it out many thanks to joe and #julemand101 I have this for UK calendar starting from sunday and ending on saturday
void main() {
final date = DateTime.parse('2021-08-01');
print('Date: $date');
final weekDay = date.weekday == 7 ? 0 : date.weekday;
print('Start of week: ${getDate(date.subtract(Duration(days: weekDay)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - weekDay - 1)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
I have 2 function:
DateTime getStartTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day);
return dateTime.subtract(Duration(days: currentDate.weekday - 1));
}
DateTime getEndTimeWeek([DateTime? date]) {
final currentDate = date ?? DateTime.now();
final dateTime = DateTime(currentDate.year, currentDate.month, currentDate.day, 23, 59, 59, 999);
return dateTime.add(Duration(days: DateTime.daysPerWeek - currentDate.weekday));
}
Below is the code which should work fine in most cases.
We can get start and end of the week like this:-
To get the first day of the week for a date use the below function.
Like Sunday (Also known as 7 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getFirstDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Sunday from the provided date
// By going back a number of weekdays from the current date to reach Sunday
DateTime firstDayOfWeekInUTC;
// If current date is not Sunday subtract days to reach Sunday
if (currentWeekDayInUTC != DateTime.sunday) {
firstDayOfWeekInUTC =
dateTimeInUTC.subtract(Duration(days: currentWeekDayInUTC));
}
// If current date is Sunday use it as the first day of week
else {
firstDayOfWeekInUTC = dateTimeInUTC;
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime firstDayOfWeekInLocal = DateTime(firstDayOfWeekInUTC.year,
firstDayOfWeekInUTC.month, firstDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return firstDayOfWeekInUTC;
} else {
return firstDayOfWeekInLocal;
}
}
To get the last day of the week for a date use the below function.
Like Saturday (Also known as 6 in WeekDay).
Read lines of comments in code for code clarifications.
DateTime getLastDayOfWeek({required DateTime currentDateTime}) {
// Converting date provided to UTC
// So that all things like DST don't affect subtraction and addition on date
DateTime dateTimeInUTC = DateTime.utc(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
// Getting weekday for the date
// For reference Sunday weekday is 7 and Friday weekday is 5
int currentWeekDayInUTC = dateTimeInUTC.weekday;
// Getting Date for nearest Saturday from the provided date
// By going forward a number of weekdays from the current date to reach Saturday
DateTime lastDayOfWeekInUTC;
// If current date is not Sunday add days enough to reach Saturday
if (currentWeekDayInUTC != DateTime.sunday) {
lastDayOfWeekInUTC = dateTimeInUTC
.add(Duration(days: DateTime.saturday - currentWeekDayInUTC));
}
// If current date is Sunday add days UpTo saturday
else {
lastDayOfWeekInUTC = dateTimeInUTC.add(Duration(days: DateTime.saturday));
}
// Converting back the date for Sunday from UTC type to Local
// You can also use UTC type depending on your use case
DateTime lastDayOfWeekInLocal = DateTime(lastDayOfWeekInUTC.year,
lastDayOfWeekInUTC.month, lastDayOfWeekInUTC.day);
if (currentDateTime.isUtc) {
return lastDayOfWeekInUTC;
} else {
return lastDayOfWeekInLocal;
}
}
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');
};
I have a date value as Fri Feb 15 19:43:05 EST 2013
I could convert it into 2013-02-15 07:43:05 as String.
Now i need to get the date object of this String. I tried using simpleDateFormat in Groovy/Grails but it would just return the original value: Fri Feb 15 07:43:05 EST 2013
The way I am doing it is:
String dateCreated = dateValue.format("yyyy-MM-dd hh:mm:ss")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //required format
Date newDate = sdf.parse(dateCreated)
Can anyone help me?
If you want dates without Time Zone I suggest you to look the Joda-Time API. There's a plugin for Grails.
Look at LocalDate and LocalDateTime, you can construct them passing separated values (year, month, day, hour, second).
If you have a Date instance, you just need:
Date dateValue = ...
String dateCreated = dateValue.format("yyyy-MM-dd hh:mm:ss")
and dateCreated will contain value like 2013-02-15 07:43:05. You don't need to do anything else