I need to get number of days from between two dates.
For example
2015.08.10 12:00 - 2015-08-12 12:00 result:2 days
i need take the result like that i did something but it doesn' work.
Template.RezSistemi.events({
"click #rezervasyonkaydet": function(event, template){
var date1_ms = template.$('#iadetarihi').val();
var date_ms=template.$('#alistarihi').val();
var formatli =date_ms-date1_ms;
alert(formatli);
}
});
As Kresten suggested, time handling is difficult without the help of a good library - and that goes for most programming languages. moment.js is a great library for javascript, which does just that.
Here is what you can do using that:
Template.RezSistemi.events({
"click #rezervasyonkaydet": function(event, template){
var date1_ms = moment(template.$('#iadetarihi').val(), "YYYY.MM.DD HH:mm");
var date_ms= moment(template.$('#alistarihi').val(), "YYYY.MM.DD HH:mm");
var days = moment.duration(date_ms - date1_ms).asDays();
alert(days + ' days');
}
});
Time handling is very hard, use a library!
MomentJS can do it:
http://momentjs.com/docs/#/displaying/to/
Falsehoods programmers believe about time:
http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time
Related
I'm trying to come up with a simple conditional format formula for highlighting cells that have a date that is greater than three months older than today's date. It seems though that the "Date is before" option only gives a few options, none of them seem to allow what I'm looking for. Is there a custom formula that could accomplish this?
Edit: attaching a snip of the column in question:
Formula :
=DAYS(now(),B2)>90
Go to the custom formula in the conditional formating rules and use this:
=DATEDIF(A1,TODAY(),"D")<90
try:
=1*C2>DATE(YEAR(TODAY()), MONTH(TODAY())+3, DAY(TODAY()))
also make sure you have valid dates and not plain text dates. you can test this with ISDATE formula
You can use Apps Script and a Custom Menu in order to solve your issue with setting the color in the cell depending on the date. Go to Tools->Script Editor and paste this code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Check Difference', 'dateDifference')
.addToUi();
}
function dateDifference(){
var sheet = SpreadsheetApp.getActiveSheet().getActiveRange(); // Get the selected range on the sheet
var dates = sheet.getValues(); // Get the values in the selected range
var oneDay = 1000*60*60*24;
var row = 1;
var re = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/; // This will help you to check if it's really a date
dates.forEach(function(el){ // Iterate over each value
if(typeof el[0] == 'object'){ // Check if it's really a date
var gmtZone = el[0].toString().split(" ")[4].split(":")[0]; // Take the date's GMT
var dateFormatted = Utilities.formatDate(el[0], gmtZone, "dd/MM/yyyy"); // Format the date
if(re.test(dateFormatted)){ // Test if it's the right format
// This part will calculate the difference between the current date and the future date
var futureDateMs = new Date(el[0]);
var todayDateMs = (new Date()).getTime();
var differenceInMs = futureDateMs - todayDateMs;
var differenceInDays = Math.round(differenceInMs/oneDay);
if(differenceInDays >= 91.2501){ // Test if the difference it's greater to 91.2501 days (3 motnhs)
sheet.getCell(row, 1).setBackground("#00FF00"); // Set the color to the cell
}
row++;
}
}
});
Save it by clicking on File->Save.
Then you can select a range in a column and click on Custom Menu->Check Difference as you can see in the next image:
As you can see, you will get the desired result:
Notice
It's really important to be careful with what you consider to be a "month", I mean how many days you are going to take into consideration. In my code, I took Google's suggestion of 1 = 30.4167.
Docs
These are other Docs I read to be able to help you:
Utilities.formatDate()
Working with Dates and Times.
I hope this approach can help you.
What is the best way to determine the correct date format (dd/mm or mm/dd) of a Google Form response.
When I use the namedValues object:
function onFormSubmit(e){
var namedValues = e.namedValues;
var date = namedValues['Date']; // Date=[05/06/2018]
var date = new Date(date);
Logger.log(date); //Sun May 06 00:00:00 GMT+10:00 2018
}
When I use the value from the spreadsheet:
function onFormSubmit(e){
var range = e.range;
var row = range.getRow();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form Responses 1');
var date = sheet.getRange(row,2).getValue();
Logger.log(date); //Mon Jun 05 00:00:00 GMT+10:00 2018
}
I don't know whether I should be, but I am hesitant using the values from the spreadsheet in an onFormSubmit trigger, since I have experienced instability in the past where I think the trigger was running before the data was being posted to the spreadsheet.
I cannot find anything in the Google Forms documentation stating whether a date response is always in a consistent format. If it was always dd/mm/yyyy I could construct the date using the string parts.
Is there a way to use determine the correct date format from the namedValues object?
P.S I would rather not use the moment.js library for this one requirement, so keen to understand if its possible without.
You Google form will constantly submit the date in the same format, but your sheet might change the appearance of formatting.
Also, there is now a date format utility built into Apps script. You can change the date string to the format that you need.
// This formats the date as Greenwich Mean Time in the format
// year-month-dateThour-minute-second.
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);
I am trying to add a day to my date:
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate);
However, this keeps returning an obscure object {_i: "2017-12-20T21:06:21+00:00", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array(7), …}
fiddle:
http://jsfiddle.net/rLjQx/4982/
Does anyone know what I might be doing wrong?
You are logging a moment object. As the Internal Properties guide states:
To print out the value of a Moment, use .format(), .toString() or .toISOString().
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Please note that you can get the current date using moment() (no need to use new Date()) or moment.utc().
I will go with this one, simple works for me and I don't think you need other function to only add day in moment.
var yourPreviousDate = new Date();
var yourExpectedDate = moment(yourPreviousDate).add(1, 'd')._d;
The add method modifies the moment object. So when you log it, you're not getting an obscure object, you're getting the moment object you're working with. Are you expecting a formatted date? Then use format or some other method.
I agree with other answers just providing shortcut and different ways
You can do the format at the same time
moment().add(1,'d').format('YYYY-MM-DD');
or you can just format any date or date object
moment(result.StartDate).format('YYYY-MM-DD');
This is my first question on stckoverflow so I hope I'm asking right.
On my website i'm using a jquery datepicker. This works fine. However, I need the following addon:
- When a user selects a date which is a specific date (var specificDate), alert with hello world.
This code already triggers the alert when selecting a date. However I am not able to figure out how to compare the "var date" with the array of specifc dates.
onSelect: function(dateText, inst){
var date = $(this).datepicker('getDate');
var specificDate = ["12-12-2013","11-12-2013"];
for (i=0; i < specificDate.length; i++){
if (date == specificDate [i]){
alert("hello world");
}
}
});
I think I need to know more about the date formats. My question is to get me a bit further with this how to make the comparison.
Thank you in advance!
Reference
if ($.datepicker.parseDate('dd-mm-yy', specificDate[0]) > $.datepicker.parseDate('dd-mm-yyyy', specificDate[1])){
alert(specificDate[0] + 'is later than ' + specificDate[1]);
}
This works in Javascript
new Date() - new Date("2013-02-20T12:01:04.753Z")
But in typescript I can't rest two new Dates
Date("2013-02-20T12:01:04.753Z")
Don't work because paremater not match date signature
Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
This is how it should be done in typescript:
(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()
Better readability:
var eventStartTime = new Date(event.startTime);
var eventEndTime = new Date(event.endTime);
var duration = eventEndTime.valueOf() - eventStartTime.valueOf();
In order to calculate the difference you have to put the + operator,
that way typescript converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes or hours.
It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.
There is a workaround for this using the + prefix:
var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z"));
Or, if you prefer not to use Date.now():
var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));
See discussion here.
Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
OP wanted a time as the result:
return new Date(this.submitted.valueOf() - this.created.valueOf())