my code below is in javascript, $('#date_start').change(function(){ is working fine, but when im using if else statement to compare the date inputted in my inputbox from the current date, nothing happens at all.
$(document).ready(function() {
$('#date_start').change(function(){
var startdate = $('#date_start').datepicker("getDate");
var today = new Date();
var tomorrow = today.add(2).day();
if(startdate.getTime() < today.getTime()){
document.getElementById('finish').disabled = true;
}
else{
Remove Time from both of Date and compare it.
String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
Related
I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this?
I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately.
function sendAlert{
var now = new Date();
var yearNow = now.getYear();
var monthNow = now.getMonth() + 1;
var dayNow = now.getDate();
var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT');
var sentYear = sheet.getRange("R2").getValue();
var sentMonth = sheet.getRange("S2").getValue();
var sentDay = sheet.getRange("T2").getValue();
if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) {
sendEmail();
var sentYear = sheet.getRange("R2").setValue(yearNow);
var sentMonth = sheet.getRange("S2").setValue(monthNow);
var sentDay = sheet.getRange("T2").setValue(dayNow);
else {
Logger.log('Alert was already sent today.');
}
}
I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again.
Requirement:
Compare dates and send an email if one hasn't been sent already today.
Modified Code:
function sendAlert() {
var sheet = SpreadsheetApp.getActive().getSheetByName('blank');
var cell = sheet.getRange(2,18); //cell R2
var date = new Date();
var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd");
var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd");
if (alertDate !== currentDate) {
sendEmail();
cell.setValue(date);
} else {
Logger.log('Alert was already sent today.');
}
}
As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate.
References:
Utilities.formatDate()
Class SimpleDateFormat
I need to check fox example 2117-09-15 00:00:41.0.
I saw similar topics but this var valid = (new Date(timestamp)).getTime() > 0;don't work.
If you want to check that a date is valid in MySQl then you could check that it is between some dates (min and max of mySql timestamp):
function isValid(dateString) {
var minDate = new Date('1970-01-01 00:00:01');
var maxDate = new Date('2038-01-19 03:14:07');
var date = new Date(dateString);
return date > minDate && date < maxDate;
}
Here is a fiddle for you to test: https://jsfiddle.net/x5hmyyrz/3/
As seen here: Checking if a date is valid in javascript, maybe you can use :
var date= new Date(timestamp)
valid = (date instanceof Date && !isNaN(date.valueOf()));
I have a requirement where i have to filter my data based on datetime.I am retrieving data in server side and passing it to client side by serializing it.My date is in format(
"2014-01-01 12:00:00").Controls i used are Telerik RadDatePicker and RadSlider, upon the change of slider value i want to filter my data by adding hours to date selected and comparing it with my data. Is there any easy way to do it in javascript which will handle all the scenarios like handling leap year scenario as the date will change when the hours will exceed 24.
This is what solve my problem.
function clientValueChange(sender, eventArgs) {
var hr = parseInt(sender._itemData[sender.get_value()].value);
if (dtWPSelDate == "")
return;
var arr = dtWPSelDate.split(' ')[0].split('-');
var dtt = new Date();
dtt.setYear(arr[0]);
dtt.setMonth(parseInt(arr[1]-1));
dtt.setDate(arr[2]);
if (eventArgs.get_oldValue() > eventArgs.get_newValue())
dtt.setHours(-hr,0,0);
else
dtt.setHours(hr,0,0);
dtt.setMinutes(0);
dtt.setSeconds(0);
if ((parseInt(hr) % 24) == 0) {
dtWPSelDate = dtt.format('yyyy-MM-dd 00:mm:ss');
}
else
dtWPSelDate = dtt.format('yyyy-MM-dd hh:mm:ss');
console.log(dtWPSelDate);
}
var dtWPSelDate ;
function DateSelected(sender, eventArgs) {
dtWPSelDate = eventArgs._newValue;
}
var dateString = "4/10/2014"; //consider this as your date in string DataType
var dateArray = dateString.split("/");
var date = new Date(dateArray[2], Number(dateArray[1])-1, dateArray[0]);
//To add Hours
var hoursToBeAdded = 10;
date.setHours(hoursToBeAdded);
Highlight point is you no need to worry about leap year which will be handled by javascript itself.
I have some code here where I get a value from a form represented by "adate". Then I split the string the user enters at the hyphen and separate each value into year, month and day as you can see. I use those values to define a date object. My console correctly displays the date, but I keep getting this error also showing up. Am I defining the date incorrectly? I'm not sure what the issue is.
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task")) return;
var adate = document.getElementById("dueDate").value;
var reString = new RegExp("[0-9]{4}\\-\[0-9]{2}\\-\[0-9]{2}");
if ( adate.match(reString)) {
processDate(adate) }
else {
alert("you did not enter the date in the correct format")
};
var id = (new Date()).getTime();
var todoItem = new Todo(id, task, who, date);
todos.push(todoItem);
addTodoToPage(todoItem);
saveTodoItem(todoItem);
hideSearchResults();
}
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
console.log(date);
}
Make your function return the date, because the date variable in there is not visible to the outside:
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
return new Date(year, month, day);
}
Then assign to a new variable when you call it:
var date = processDate(adate);
The error actually originated in the following line, because you were referencing a non-existing date variable:
var todoItem = new Todo(id, task, who, date);
Just a comment.
The RegExp constructor is usually only required where the expression is dynamically generated. Where you have a fixed expression, it's simpler to use a literal (as you don't have to quote certain characters). Also, to test the format, a more appropriate method is test rather than match.
If the date format is: yyyy-mm-dd, consider:
var reString = /^\d{4}-\d\d-\d\d$/; // trim leading and trailing white space?
if (reString.test(adate)) {
processDate(adate);
}
The date string validation should be in the processDate function, which might throw different errors depending on whether the format is incorrect or the date is invalid (e.g. 2013-02-29, which will return a date of 2013-03-01 in your current code).
I want to compare the selected date and current date. Iam using jquery date picker. While using the following code only the date field comparison is takes place... How can i compare with month and year also... Advance thanks..
$(document).ready(function() {
var objDate = new Date();
var selectedDate = document.getElementById("<%=txtRqstDate.ClientID %>").value;
var currentDate = $.datepicker.formatDate('dd/mm/yy', new Date());
if (Date.parse(selectedDate) > Date.parse(currentDate )) {
alert("Invalid date range!\n Please choose a date that is not later than today!")
return false;
}
else {
return true;
}
Pls use this.I thing it will solve ur problem
function ChDate(){
var objDate = new Date();
var selectedDate = document.getElementById("<%=txtRqstDate.ClientID %>").value;
if (selectedDate > objDate ) {
//do
}
else
{
//do
}
}
Pls chk the following link to get more functions
http://www.w3schools.com/jsref/jsref_obj_date.asp
It is possible to take split an do checking by using string.split(separator, limit)