Get time difference between two date strings - javascript

I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?

If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}

Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.

Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);

As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.

Related

Return the date format for date without moment.js

I can't figure out how to build a function that does this
INPUT: dateToDateFormat('16/07/2022') -> OUTPUT: DD/MM/YYYY
INPUT: dateToDateFormat('07/16/2022') -> OUTPUT: MM/DD/YYYY
The input dates will be already formatted by .toLocaleString function
Edit:
I think I was not precise enough with the output, it should literally output MM/DD/YYYY as a string, not the actual date value
A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.
B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.
A) CONVERSION
Seems you need a simple swap of day and month in your date string?
In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js.
You can use the following function:
const date1 = "16/07/2022"
const date2 = "07/16/2022"
const dateToDateFormat = (date) => {
const obj = date.split(/\//);
return `${obj[1]}/${obj[0]}/${obj[2]}`;
};
console.log("New date1:", dateToDateFormat(date1))
console.log("New date2:", dateToDateFormat(date2))
B) STRING TO DATE
Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant.
However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
console.log("dateFormat1", dateFormat1);
console.log("dateFormat2", dateFormat2);
dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).
CHECK VALIDITY
In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
function isDateValidFormat(date) {
return date instanceof Date && !isNaN(date);
}
console.log("JS Date Object?", isDateValidFormat(dateFormat1));
console.log("JS Date Object?", isDateValidFormat(dateFormat2));
Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).
CONVERT TO DATE OBJECT BY KNOWING THE FORMAT
The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.
const newDate1 = "07/16/2022"
const newDate2 = "16/07/2022"
function convertToValidDateObject(date, inputFormat) {
const obj = date.split(/\//);
const obj0 = Number(obj[0])
const obj1 = Number(obj[1])
const obj2 = obj[2]
//
// CHECK INPUT FORMAT
if (inputFormat === "MM/DD/YYYY") {
return new Date(obj2, obj0-1, obj1+1);
} else if (inputFormat === "DD/MM/YYYY") {
return new Date(obj2, obj1-1, obj0+1);
} else {
return "ERROR! Check, if your input is valid!"
}
}
console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))
If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).
I wish you good luck. Hope these information can help you.

How to get the difference between two dates with php and symfony 4?

I am developing a holiday management project. There is an entity called Conge which includes date_departure, date_retrun and period. I made a form and the view. I would like to set the difference between the date of departure and the date of return. For example, if the user chooses dates from '04-05-2019' to '04-08-2019', how can I get and display the difference in days using javascript, php, and symfony4?
If you are always going to use the m-d-Y format for your dates you can use just PHP to give you the number of days difference.
$departure ="04-05-2019";
$arrival = "04-08-2019";
$departure = DateTime::createFromFormat('m-d-Y', $departure)->getTimestamp();
$arrival = DateTime::createFromFormat('m-d-Y', $arrival)->getTimestamp();
echo ($arrival - $departure) / (24*60*60); // 86400 might save some math
Use momentjs (https://momentjs.com/docs/#/displaying/difference/)
var departureRaw = $(".departure").val();
var departureDate = moment(departureRaw);
var returnRaw = $(".return").val();
var returnDate = moment(returnRaw);
var difference = departureDate.diff(returnDate, 'days');
for php, as mentionned here and here you can use ->diff() function. I don't think than Symfony have any function for that

Show yyyyww (yearweek) in Google Scripts / Javascript (Sunday-Monday)

I'm really struggling to do a clean, efficient way of showing yearweek for Sunday to Monday
e.g.:
201624
201625
201626
201627
201628
Is there an efficient way to do so in Google Scripts or Javascript without using a library?
Thanks!
Found a solution! :
var yearMonth = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "yyyyww")).toFixed(0);
It was provided by user: Balu Ertl at Get week of year in JavaScript like in PHP
I would use Moment.js. Documentation for the use can be found here for the format you are looking for http://momentjs.com/docs/#/displaying/.
To have it work with google script you will need to first add it to the libraries using MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48, then you need to load it in using something like var moment = Moment.load().
From here you can get the month and year already formatted into your requested format.
var date = getDate();
var wwyy = moment(date).format('wo, YY');
My appologies, my format wasn't exactly as you wanted it to be. To answer in the format you are looking for:
var date = new Date();
var yyyyww = moment(date).format('YYYY ww');

moment.js compare dates via .diff()

Im having problems when I try to compare 2 dates.
var end = moment(items[i].dateEnd).format('DD/MM/YYYY');
var now = moment().format('DD/MM/YYYY');
Example: now = '29/10/2015' and end = '30/06/2015'
Tried using .diff() function from moment.js without any result, like this:
end.diff(now);
Any help?
Thanks.
You can try with specifying input date format:
moment(items[i].dateEnd, 'DD/MM/YYYY').diff(moment());

manipulating date object with javascript

i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5

Categories