I am new in the world of programming: D and I have a doubt about the comparison of hours.
I have a sheet with the following information
Name | Time out | Time in |
nam_1 10:00:00
nam_2 09:00:00
Time out hours have been entered using this code:
var start = Utilities.formatDate (new Date (), "Europe / Berlin", "HH: mm: ss");
sheet.appendRow([name, start]);
What I would like to try is:
var time_in = "13:00:00";
if time out> 13:00:00:
sheet.getRange(j+1, 2).setValue(time_in);
The problem is that I do not know exactly how to do it. What I have tried for now is:
function getTimeFromDateStartUserInput(date) {
return Utilities.formatDate(date, "Europe/Berlin", "HH:mm:ss");
}
function insertTimeIn(){
var file = DriveApp.getFilesByName("MySheet");
var doc = SpreadsheetApp.open(file.next());
var sheet = doc.getSheetByName("Sheet1");
if(sheet!=null){
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var time_in = new Date ('30/12/1899 17:00:00');
time_in.setHours(13,0,0,0);
var inFormated = getTimeFromDate(time_in);
for(var i = 0; i<values.length; i++){
if(values[i][1]>=inFormated && values[i][2]=""){
sheet.getRange(j+1, 2).setValue(time_in);
}else{
sheet.getRange(j+1, 2).setValue("Nop");
}
}
}
However, I have not achieved anything with that code.
I think the problem may be that any entry in the "Time out" column has this design: Sat Dec 30 14:51:22 GMT + 01: 00 1899.
Therefore I think it does not work since I am comparing an hour with a complete Date object.
The logical thing I think it would be to call the function getTimeFromDateStartUserInput for all the input of values[i][1] but I do not know how to do it.
Could someone help me with this problem?
This is my guess at what you are trying to do. It doesn't work because it still contains errors. I commented on a few of them but I can't fix them because it's still not clear what you are trying to do..
function insertTimeIn(){
var files = DriveApp.getFilesByName('SpreadsheetName');
var n=0;
while(files.hasNext()){
var file=files.next();
}
if(++n>1){
throw("Error: There is more than one file with that name in function insertTimeIn");
return;
}
if(file.getMimeType()==MimeType.GOOGLE_SHEETS){
var doc=SpreadsheetApp.openById(file.getId());
var sheet=doc.getSheetByName("Sheet1");
if(sheet!=null){
var dataRange=sheet.getDataRange();
var values=dataRange.getValues();
var time_in=new Date(1899,11,30,13,0,0);
var inFormated=Utilities.formatDate(time_in, Session.getScriptTimeZone(), "HH:mm:ss");//it returns a string not a date
for(var i=0;i<values.length;i++){
if(values[i][1]>=inFormated && values[i][2]=""){//informated is a string not a date so greater than doesn't really make much sense here.
sheet.getRange(j+1, 2).setValue(time_in);//j is undefined
}else{
sheet.getRange(j+1, 2).setValue("Nop");//again j is undefined
}
}
}
}
}
A simple answer might be to auto convert the initial timestamp to the current date. I'm not entirely sure what the use of your sheet is going to be but I use a sheet for time entry and use the function onEdit() to verify that the user put the dateTime in correctly.
function onEdit(){
if(cell.getValue() instanceof Date === true){
if(cell.getValue().getFullYear()<2018 ){
formatDate();
}
}
}
function formatDate() {
var timeValue, cell,hour,minute,time,row,dateObj,month,day,year,newDate
cell = SpreadsheetApp.getActive().getActiveCell()
timeValue = cell.getValue()
hour = timeValue.getHours()
minute = timeValue.getMinutes() < 10? '0'+timeValue.getMinutes(): timeValue.getMinutes();
time = hour+":"+minute
row = cell.getRow()
dateObj = new Date();
month = dateObj.getUTCMonth() + 1; //months from 1-12
day = dateObj.getUTCDate();
year = dateObj.getUTCFullYear();
newDate = month + "/" + day + " "+ time; // formatted dateTimestamp to replace timestamp with
cell.setValue(newDate)
}
Let me know if that works for you. In my application, the onEdit function checks the active cell and continues if the entered value is a dateTime. If it is, it check what year the date is (time values alone are automatically 12/30/1899 and therefore throw wild numbers out when getting durations between a dateTimestamp and a timestamp with no date.
Related
Image of my array valuesI have a function to "Wed 12/8" and "Wed 12/8". However, when I use them in this function they are not equal for some reason yet they are identical. The function does not append and acts as if they are completely different.
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i] == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
Here the get date code.
//Date
var now = new Date();
//Gets the current days date
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['1','2','3','4','5','6','7','8','9','10','11','12'];
var weekday = days[now.getDay() - 1];
var day = now.getDate() - 1;
var month = months[now.getMonth()];
var today = weekday + " " + month + "/" + day;
//Console logs todays date
console.log(today);
The values are the exact same but the computer thinks they are not. When I manually change today to "Wed 12/8" it works but the variable seems to mess it up though I may be wrong. What's happening and how do I fix this as it is crucial to my program?
The problem should be the way you populate the dateList array. Are you sure it gets filled with strings too, and not for example date objects? The code you provided does not show anything related to that array.
Edit:
Based on the image you provided later, I think the issue will be that your strings in the array contain quotation marks.
Remove them from the strings. (For example by slicing the first and last characters from it in the filterDate function)
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i].slice(1,-1) == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
I'm facing issue with excluding weekend dates in JavaScript.For my business requirement I want to exclude 3 days from date object Friday, Saturday and Sunday in every week.What I need here is the values of Friday should display as Monday, Saturday as Tuesday and Sunday as Wednesday. I'm able to do this.
The issue that I'm facing here is when we run the above example the a[0] value should be 21-SEP-2017 but I'm getting 20-SEP-2017 and remaining array values should not change. So please do help me out in resolving this issue
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"];
for (i = 0; i < a.length; i++) {
var startDate = a[i];
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "",
noOfDaysToAdd = 1;
var count = 0;
endDate = new Date(startDate.setDate(startDate.getDate()));
if (startDate.getDay() != 0 && startDate.getDay() != 5 && startDate.getDay() != 6) {
endDate = new Date(startDate.setDate(startDate.getDate() + i - 1));
} else {
startDate.setDate(startDate.getDate() + 3)
endDate = new Date(startDate.setDate(startDate.getDate()));
}
console.log(endDate); //You can format this date as per your requirement
}
Your code seems not finished: the variables noOfDaysToAdd and count are never used, and if they were, they would be reset in every iteration of the loop, which cannot be the purpose.
That your output shows 20 September is because you did not output a stringified version of the date, but the date object itself, and then console.log will display the date as a UTC date (notice the time part matches the timezone difference). Instead use .toString() or another way to turn the date to a localised string.
Here is how you could do it:
function toDate(s) {
return new Date(s.replace(/-/g, '/'));
}
function toStr(dt) {
var months = ["JAN","FEB","MAR","APR","MAY","JUN",
"JUL","AUG","SEP","OCT","NOV","DEC"];
return [('0'+dt.getDate()).substr(-2), months[dt.getMonth()], dt.getFullYear()]
.join('-');
}
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"],
add = 0;
var result = a.map(toDate).map(dt => {
dt.setDate(dt.getDate()+add);
var move = [0, 6, 5].indexOf(dt.getDay()) + 1;
if (move) {
add += move;
dt.setDate(dt.getDate()+move);
}
return dt;
}).map(toStr);
console.log(result);
Hi I need to store every year directly from the date of entry of a user to the business the problem is that every time I add a year is inserted between the day and month.
var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow();
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
console.log(dateStart);
//03-12-2009
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart, "DD-MM-YYYY").add(1, 'years').calendar();
yearsOfWork.push(dateStart);
}
console.log(yearsOfWork);
Result of this:
0:"12/03/2010"
1:"03/12/2011"
2:"12/03/2012"
3:"03/12/2013"
4:"12/03/2014"
5:"03/12/2015"
6:"12/03/2016"
7:"03/12/2017"
This is a subtle error! According to the moment docs https://momentjs.com/docs/#/displaying/ .calendar() uses a default date format, possibly using the locale of the environment, if none is provided, so here it looks like it's defaulting to MM/DD/YYYY, rather than the desired DD/MM/YYYY. So on the first iteration dateStart is converted to 12/03/2010 with the month and day swapped. Then on the next iteration it's converted back to DD-MM-YYYY, again with the day and month swapped, then when passed to .calendar() again the day and month swap again giving the correct format again.
A potential bug is that you're changing dateStart from a string to a moment object, so I'd rewrite the code like this:
var dateStart = moment(user.fecha_ingreso_empresa).format("DD-MM-YYYY");
var f = parseInt(yearOnCompany);
var yearsOfWork = [];
for(var i = 1; i <= f; i++)
{
dateStart.add(1, 'years');
yearsOfWork.push(dateStart.format("DD-MM-YYYY"));
}
console.log(yearsOfWork);
I think you have the problem with the format, correct me if I am wrong.
Please try this.
for(var i = 1; i <= f; i++)
{
dateStart = moment(dateStart , "DD-MM-YYYY").add(1, 'years');
yearsOfWork.push(dateStart.format('DD-MM-YYYY'));
}
Ive got a piece of JS that needs to validate and compare a start date and time against an end date and time.
So in other words end date & time cannot be less than start date and time.
Now the problem.
I originally only accepted the time in 24 hour(military) Format. but now let the user choose between 12 hour or 24 hour.
Example 13:00 or 1:00 PM
This piece of code work for 24 hour time format, but not for 12, its 12:00 PM that causes the problem.
So I need to adapt this piece of code to work for either 12 hour or 24 hour, but im not sure how to do this.
function validateStartEndTime() {
var date = document.getElementById("datepickerStart").value;
var dateEnd = document.getElementById("datepickerEnd").value;
if (!isValidDate(date)) {
alert("Not Valid Date");
return false;
}
var start = document.getElementById("timepicker").value;
var end = document.getElementById("timepickerEnd").value;
var stDate = new Date(parse(date +" "+ start));
var enDate = new Date(parse(dateEnd + " "+ end));
var compDate = enDate - stDate;
if (compDate >= 0)
return true;
else {
alert("End time must be greater than Start Time ");
return false;
}
}
You could write a function that converts time in 12 hour format to time in 24 hour format, something like:
function convertTo24HourFormatIfNeeded(timeString) {
var is12HourFormat = timeString.indexOf("M") !== -1;
if (is12HourFormat) {
var isPm = timeString.indexOf("PM") !== -1;
var timeStringNoSuffix = timeString.split(" ")[0];
if (isPm) {
var hoursAndMinutes = timeStringNoSuffix.split(":");
var hours = hoursAndMinutes[0];
var convertedHours = (Number(hours) + 12);
var minutes = hoursAndMinutes[1];
return convertedHours + ":" + minutes;
} else {
return timeStringNoSuffix;
}
} else {
return timeString;
}
}
Then use it in your code:
var start = convertTo24HourFormatIfNeeded(document.getElementById("timepicker").value);
var end = convertTo24HourFormatIfNeeded(document.getElementById("timepickerEnd").value);
If you're not adverse to using external libraries, i found MomentJs to be very handy working with dates, and among other things it allows to parse the date in a user-defined format, so you could build your date string accordingly to user selection of AM/PM or 24-hour format and feed it to moment js.
I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.
I am having a hard time finding out how to do this, my current code won't work.
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
function parseDate() {
var date = $('#date').val();
var parsedDate = Date.parse(date);
alert('Parsed date: '+parsedDate);
}
function jämförMedIdag (datum) {
if (datum == null || datum == "") {
alert('Inget datum!');
return;
}
/*resultat = Date.compare(Datum1,Datum2);
alert(resultat); */
var datum = Date.parse(datum);
var dagar = datum.getDate();
var månader = datum.getMonth();
var år = datum.getYear();
var nyttDatum = new Date();
nyttDatum.setFullYear(år,månader,dagar);
var idag = new Date();
if(nyttDatum>idag) {
var svar = nyttDatum - idag;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
} else {
var svar = idag - nyttDatum;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
}
}
</script>
This code will try to calculate the difference between two dates, one of them being today. No success lolz.
Thanks in advance!
My final code (thanks RobG!):
function dateDiff(a,b,format) {
var milliseconds = toDate(a) - toDate(b);
var days = milliseconds / 86400000;
var hours = milliseconds / 3600000;
var weeks = milliseconds / 604800000;
var months = milliseconds / 2628000000;
var years = milliseconds / 31557600000;
if (format == "h") {
return Math.round(hours);
}
if (format == "d") {
return Math.round(days);
}
if (format == "w") {
return Math.round(weeks);
}
if (format == "m") {
return Math.round(months);
}
if (format == "y") {
return Math.round(years);
}
}
It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.
If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:
Example
// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY
var start = Date.parse("20.09.2011");
var end = Date.parse("28.09.2011");
var span = new TimeSpan(end - start);
span.days; // 8
Of course the above could be simplified down to one line if you really want to be extra terse.
Example
new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
Hope this helps.
If your dates are strings in the common form d/m/y or some variation thereof, you can use:
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.
Edit to answer comments
To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:
var s = s.split(/[/\.-]/);
The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].
/Edit
To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).
So if you want to see how many days are between today and a date, use:
function diffToToday(s) {
var today = new Date();
today.setHours(0,0,0);
return Math.round((toDate(s) - today) / 8.64e7);
}
alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365
PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.
Using the Date object:
var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
var prevMonthDate = dateToday.addDays(-30);
var difference = (dateToday - prevMonthDate)/86400000;
console.log(difference); //will give you the difference in days.