in the particular google scripting logic I have a requirement where I need to set a flag to true if the given date is a weekday or if it is a month-end.
Example:
the flag should be set to true if the date is 5/11/2020 or 5/15/2020 or 5/31/2020. However, the flag should remain false for the dates like, 5/16/2020 or 5/30/2020
Please let me know if there are any built in functions or any code snippets that I can enhance myself.
Regards
KK
You can work with the JavaScript Date object and compare getDay() to 0 or 6 for weekends, in which case flag is false.
For the month end, there are many ways to do it, but I find adding a method to Date.prototype is a nice way to go about this. So you would add 1 day to the date and compare the months, flag is true if they are different.
Example:
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function flagDate() {
var today = new Date();
var flag;
if(today.getDay()==6 || today.getDay()==0){
// Today is weekend
flag = false;
} else{
flag = true;
}
if(today.addDays(1).getMonth() != today.getMonth()){
// Today is the end of the month
flag = true;
}
return flag;
}
References:
Date()
To capture the day of the week use Date.getDay() and then check it against your requirements. Remember that 0 = Sunday, 1 Monday, etc…:
const someDate = isWeekday( new Date() ); // This is the date you are checking
// if it is weekday
if( date.getDay() != 0 || date.getDay() != 6 ){
// do something
} else {
// if it is weekend, do something esle
}
Alternatively you can add this to the Date.prototype.
https://www.tutorialspoint.com/javascript/date_getday.htm
Related
Using iOS16.3, XCode14.2, Swift5.7.2,
Why is the following method no longer working ?
I call this method by setting date = Date() and maximumDate = Date() as well...
According to this solution, it should work - but it doesn't
public class THManager : ObservableObject {
#Published public var minimumDate: Date = Date()
#Published public var maximumDate: Date = Date()
public func isBetweenMinAndMaxDates(date: Date) -> Bool {
print(min(minimumDate, maximumDate))
print(max(minimumDate, maximumDate))
print(min(minimumDate, maximumDate)...max(minimumDate, maximumDate))
print(date)
print((min(minimumDate, maximumDate)...max(minimumDate, maximumDate)).contains(date))
return (min(minimumDate, maximumDate)...max(minimumDate, maximumDate)).contains(date)
}
}
2022-02-08 19:45:51 +0000
2023-02-03 19:45:51 +0000
2022-02-08 19:45:51 +0000...2023-02-03 19:45:51 +0000
2023-02-03 19:45:51 +0000
false
It supposed to return true ! Why does it return false ???
By the way it works if date = Date() and maximumDate = Date().addingTimeInterval(1)
Very strange, isn't it ?
There is no need for such complexity. Date objects conform to the Comparable and Equatable protocols, so testing for a date being between 2 other dates is one line:
extension Date {
func between(start: Date, end: Date) -> Bool {
return self > start && self < end
}
}
You'd use that like this:
let date = Date()
if date.betweeen(start: someDate, end: someOtherDate) {
// the date is between the start and the end
} else {
// The date is not between the start and end dates
}
The above will only return true if the date in question is not equal to start or end date. You could easily change it to match dates that match the beginning and end dates by using >= and <= instead of > and < in the comparisons.
And as discussed in the comments, Date objects have sub-millisecond precision. Two dates that appear identical may be different by a tiny fraction of a second, the best way to verify your comparisons is to convert your Dates to decimal seconds and log the seconds values. (See the Date property timeIntervalSinceReferenceDate.)
Edit:
Check out this sample code using the above exension:
extension Date {
func between(start: Date, end: Date) -> Bool {
return self > start && self < end
}
var asStringWithDecimal: String {
return DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .medium) + " ( \(self.timeIntervalSinceReferenceDate) seconds)"
}
}
let now = Date()
for _ in (1...5) {
let random = Double.random(in: -1.5...1.5)
let test = now.advanced(by: random)
let start = now.advanced(by: -1)
let end = now.advanced(by: 1)
let isBetween = test.between(start: start, end: end)
let isOrNot = isBetween ? "is" : "is not"
let output = "\(test.asStringWithDecimal) \n \(isOrNot) between \n \(start.asStringWithDecimal) and \n \(end.asStringWithDecimal)"
print(output)
}
That will generate 5 random dates ± 1.5 seconds from the current date, and then test each one to see if it is within 1 second of the current date. It logs the result as both Date strings and Doubles, so you can see what's happening when the seconds match (but the fractions of a second likely don't match.)
So, I'm working on a converter for changing JDE Julian Dates to Gregorian Dates and Vice Versa. I've run into a weird problem that I cannot find an answer for in my Julian to Gregorian code where non-leap years are calculating as leap years and leap years are calculating as non-leap years.
Exp: When I enter the JDE Julian Date '122095' it should return 04/05/2022 but instead returns 04/06/2022. When I changed the year to 2020, a leap year, it returned todays correct date of 04/05/2022 when it should have returned 04/04/2020.
I think the problem might be with my DateTime.fromMillisecondsSinceEpoch converter because it is return 2022-04-06 06:00:00.000Z and I don't know where the 6 in the hour spot is coming from or how to cancel it out. My Code is below.
Edit: I forgot, I used the code originally from THIS post.
Edit Edit: Okay that fixed the problem, I set "var millisecondsSinceEpoch = DateTime(convYear()).millisecondsSinceEpoch;" to "var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;" and it was still giving me the wrong answer. I then thought to take the "isUtc: True" off of the end of "var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear));" and that fixed the issue. The best I can figure is having the UTC bool at the end of that line was preventing millisecondsSinceEpoch from actually converting to UTC.
Thanks jamesdlin and James Heap for your help!
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
gregDate(var inputDate) {
var inputDate = '122095';
// Break down JDE date into individual pieces
var currentYear = int.parse(DateFormat('yy').format(DateTime.now()));
print('Current Year: $currentYear');
var splitYear = int.parse(inputDate.substring(1, 3));
print('Split Year: $splitYear');
var splitDay = int.parse(inputDate.substring(3, inputDate.length));
print('Split Day: $splitDay');
// Uses the current year to determine if our 2 digit date needs a 19 or 20 in the front
convYear() {
if (splitYear <= currentYear) {
var year = '20' + splitYear.toString();
return int.parse(year);
}
else {
var year = '19' + splitYear.toString();
return int.parse(year);
}
}
print('Converted Year: ${convYear()}');
// Takes 3 digit day in year and converts it to formatted date time.
convDate() {
var dayOfYear = splitDay;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
print(millisInADay);
var millisDayOfYear = dayOfYear * millisInADay;
print(millisDayOfYear);
var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;
print(millisecondsSinceEpoch);
var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear), isUtc: true);
var result = DateFormat('MM/dd/${convYear()}').format(dayOfYearDate);
print(dayOfYearDate);
print(result);
return result;
}
return convDate();
}
Hi i want to compare column with date (i.e "Referral Date" column)
with present day , here is what i have
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
for (i=0;i<range.getLastRow();i++){
var dates = searchRange.getValues();
if (today.valueOf()>dates.valueOf()){
updatelFilter()
} else{
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
The problem i have is, it throws alert Future Date Error irrespective of date in column (Referral Date). Let me know if additional information is required.
My goal:
1)if date column (Referral Date) is greater than present date : Throw alert error & should not run updateFilter
2)if (Referral Date) is lesser than present date: Run updateFilter function
Issues
searchRange.getValues() yields a two dimensional array. So dates[0][0] points to a date, while dates[0] points to an array.
var dates = searchRange.getValues(); is being called inside the loop repeatedly, when it should ideally be called outside once since the value will not change; calling it inside the loop is costly and redundant
for (i=0;i<range.getLastRow();i++){ the condition can be replaced with i<dates.length if point 2 is followed
if (today.valueOf()>dates.valueOf()){ I believe is supposed to have dates[0] instead
Modified Code
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
var dates = searchRange.getValues().map(d=>d[0]);
for (i=0;i<dates.length;i++) {
if (today.valueOf()>dates[i].valueOf()){
updateFilter()
} else {
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
To run updateFilter only if no future dates
Replace the loop with the following -
if(dates.some(d => today.valueOf() < d.valueOf())) {
SpreadsheetApp.getUi().alert('Future Date Error');
} else {
for (let i=0; i<dates.length; i++) {
updateFilter();
}
}
I have to compare two dates.
The first one I get from the TMaskEdit component with the DD-MM-YYYY mask.
I get the second date from the Date() function.
I tried something like this:
String MaskEditDate = me3->Text.Trim();
String ActualDate = Date().FormatString("DD-MM-YYYY");
TDate TDMaskEditDate = StrToDate(MaskEditDate);
TDate TDActualDate = StrToDate(ActualDate);
if (TDMaskEditDate > TDActualDate)
{
ShowMessage("TDMaskEditDate > TDActualDate");
}
if (TDMaskEditDate == TDActualDate)
{
ShowMessage("TDMaskEditDate == TDActualDate");
}
if (TDMaskEditDate < TDActualDate)
{
ShowMessage("TDMaskEditDate < TDActualDate");
}
But, when I try to convert a string to a date, I get an error message like '2000-01-01' is not a valid date and I do not know why.
StrToDate() parses the input string according to the format specified by the global ShortDateFormat and DateSeparator formatting variables in the SysUtils unit. Those variables are initialized at app startup to your OS's current user locale. This is documented behavior in BCB's help file.
So clearly, one of the input strings you pass to StrToDate() does not match the format that your OS is using for dates, which is why you get the error.
To do what you are attempting, you would have to update those formatting variables to match the format used by your input (as the overloaded version of StrToDate() that takes a TFormatSettings as input did not exist yet in BCB6). And there is absolutely no reason to take a TDate from Date(), convert it to a String, and then parse it back into a TDate, that is just redundant.
Try this instead:
String MaskEditDate = me3->Text.Trim();
TDate TDActualDate = Date();
String oldShortDateFormat = ShortDateFormat;
Char oldDateSeparator = DateSeparator;
ShortDateFormat = "DD-MM-YYYY";
DateSeparator = '-';
TDate TDMaskEditDate = StrToDate(MaskEditDate);
ShortDateFormat = oldShortDateFormat;
DateSeparator = oldDateSeparator;
However, you really should not be using a T(Mask)Edit for date input anyway. A much safer option is to use the TDateTimePicker control instead. Set its Kind property to dtkDate and then read its Date property when needed. There is no need to process your date values using strings at all:
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
if (TDDateTimePickerDate > TDActualDate)
{
ShowMessage("TDDateTimePickerDate > TDActualDate");
}
else if (TDDateTimePickerDate == TDActualDate)
{
ShowMessage("TDDateTimePickerDate == TDActualDate");
}
else //if (TDDateTimePickerDate < TDActualDate)
{
ShowMessage("TDDateTimePickerDate < TDActualDate");
}
Alternatively:
#include <DateUtils.hpp>
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
switch (CompareDate(TDDateTimePickerDate, TDActualDate))
{
case GreaterThanValue:
ShowMessage("TDDateTimePickerDate > TDActualDate");
break;
case EqualsValue:
ShowMessage("TDDateTimePickerDate == TDActualDate");
break;
case LessThanValue:
ShowMessage("TDDateTimePickerDate < TDActualDate");
break;
}
I am getting the date from CJuidatepicker with language such de,en,nl.
Now i need to find the difference between two dates in jquery accordnig to the language selected.
My Code is
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate()-1;
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day;
var dateString1 = $('#Jobs_valid_date').val();
var dateString2= output;
var dateDiff = function ( dateString2, dateString1 ) {
var diff = Math.abs(dateString2 - dateString1);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000);
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000);
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000);
} else {
return "< 1 minute";
}
};
var new_date = dateDiff(new Date(dateString2), new Date(dateString1));
var sum = (parseInt(new_date * feature) + parseInt(fixed))
It retuns NAN.. Please help me to solve this
Doing it from scratch is not recommended for several reasons. If using a library is not a constraint, use moment.js. It has methods to calculate date differences. It has internationalization support too. In case your locale is not supported you can add it yourself. If you add a new locale, you are welcome to contribute it to the moment.js community.
Try this out, this worked for me. I wanted to calculate difference between the 2 dates which the client inputs.
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}