Formatting dates when getting days between 2 dates with JQuery/Javascript - javascript

I am trying to calculate the days between 2 dates and it is working as far as I can tell but I keep getting stupidly high numbers which clearly isn't right, I have a feeling this is the way my dates are set out. my dates are set out as dd/mm/yyyy and this is the code I am using:
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
This is the question I used to get the answer:
JavaScript date difference Days
When it writes to the console this is the result I get:
diff=>17301.95833332176

I have had a play with the code, although I have not used HTML, i set the vars statically below.
var end_date = new Date("May 25, 2017");
var start_date = new Date("May 23, 2017");
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I have also checked it with a 3 value date format
var end_date = new Date(2017,4,25);
var start_date = new Date(2017,4,23);
var diff = new Date(end_date - start_date);
var days = diff/1000/60/60/24;
console.log("diff=>"+days);
I manage to get an output of 2. Which is what i expected. The code you supplied looks ok to me. Maybe look at the HTML to check that the values being passed are in the correct format.
Jquery datepicker may be of help to you here.

You could also use moment: https://momentjs.com
var moment = require('moment');
var start_moment = moment(start_date);
var end_moment = moment(end_date);
var days = start_moment.diff(end_moment, 'days');
console.log("diff=>" + days);
You can also get weeks, months etc. with this method

Easy solution, is to use countBtw
var { date } = require('aleppo')
//..
date.countBtw('all', date1, date2)

Related

Convert string to date and alter that date

Good day, I am generating 3 dates from a string, I hope the output was:
billing date: 2020/01/11
cutoff start: 2019/11/11
cuttof end: 2019/12/10
but I get the following:
billing date: 2020/11/10
cutoff start: 2019/11/10
cuttof end: 2019/12/10
I would like to know how javascript works with variables or what is the problem since everything is altered
var month = "Jan-20"
var coverage_month_obj = moment(month, 'MMM-YY').toDate();
var billing_date = new Date(coverage_month_obj.setDate(coverage_month_obj.getDate() + 10))
var cutoff_end = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
cutoff_end = new Date(billing_date.setDate(billing_date.getDate() - 1))
var cutoff_start = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
I would like to know how javascript works with variables or what is the problem since everything is altered
Put simply, calling setXXX on a javascript date variable updates that variable in place. ie, it is what we would call "mutable". You might have assumed dates were immutable and did not change in place.
To answer on a better way to achieve your goal, I'd suggest using the other functionality of momentjs to calculate your 3 dates from the given input string.
var month = "Jan-20"
var coverage_month = moment(month, 'MMM-YY');
//Jan-20 I need to convert it into date format and that the day is 11 (2020/01/11) cutoff start, are two months less from that date (2020/11/11) and cutoff end is one month less from Jan-20, but ends on day 10 (2020/12/10)
var billing_date = coverage_month.clone().add(10, 'days');
var cutoff_start = billing_date.clone().subtract(2, 'months');
var cutoff_end = billing_date.clone().subtract(1,'months').subtract(1,'day')
console.log("billing_date",billing_date);
console.log('cutoff_start',cutoff_start);
console.log('cutoff_end',cutoff_end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month

I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){
var lastRow = outputSheet.getLastRow();
var newDate = new Date();
var lastDate = outputSheet.getRange(lastRow,1).getValue();
var newDateRng = outputSheet.getRange(lastRow+1,1);
Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
newDate.setDate(lastDate.getDate());
Logger.log(newDate);
newDate.setDate((newDate.getDate() + 1));
Logger.log(newDate);
var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
Logger.log(newDateFormatted);
newDateRng.setValue(newDateFormatted);
}
With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks
You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var date = new Date(lastDate); // create new date object
var result = [];
for (var i=0;i<365;i++){
date=new Date(date).setDate(new Date(date).getDate()+1)
Logger.log('date='+new Date(date))
result.push([new Date(date)]);
}
SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

How can I get the correct form of JavaScript and Ruby timestamp?

I have this datetime stamp from Ruby:
2017-10-06 05:11:53 UTC
This datetime stamp from JavaScript:
"2017-10-07T12:07:06.694Z"
Is there a method to which I could find out the difference in seconds?
How do I convert from a ruby timestamp to a javascript timestamp?
You could do this using Ruby with strftime or directly in javascript as demonstrated by Tavish.
var myDate = new Date('2017-10-06 05:11:53 UTC')
How do I find the difference in seconds between two timestamps with Javascript?
var past = new Date('2017-10-06 05:11:53 UTC');
var future = new Date('2017-10-07T12:07:06.694Z');
var deltaInMilliseconds = future.getTime() - past.getTime();
var deltaInSeconds = deltaInMilliseconds / 1000;
console.log(deltaInSeconds)
There are lot of ways to do so. One way is:
var myDate = new Date('2017-10-06 05:11:53 UTC')
console.log(myDate)
var myDate1 = new Date('2017-10-07T12:07:06.694Z')
console.log(myDate1)
var difference = myDate.getSeconds() - myDate1.getSeconds()
console.log(`Seconds passed: ${difference}`)

NaN javascript error when calculating between dates with timestamp

I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}
Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));
The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);
You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);
for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?

Categories

Resources