How to find between 2 dates whichever comes first - javascript

I tried to find someone between 2 dates earlier in the year or month and it didn't work
converteDateToDatePipe(dCheck: Date, d1: Date): boolean {
var d11 = this.pipe.transform(d1, 'shortDate');
var dCc = this.pipe.transform(dCheck, 'shortDate');
var dd11 = new Date(d11);
var ddcc = new Date(dCc);
if (dd11 <= ddcc)
return true;
else
return false;
}

test(){
let first = new Date(new Date().getTime() + 111111);
let second = new Date(new Date().getTime() + 22222);
let nextDate = this.nextDate(first, second);
console.log(second.getTime() === nextDate.getTime())
}
nextDate(first: Date, second: Date): Date {
let currentDay = new Date();
let firstDiff = currentDay.getTime() - first.getTime();
let secondDiff = currentDay.getTime() - second.getTime();
return (firstDiff >= secondDiff) ? first : second;
}

Related

How to get starting and ending days of each month in a date interval in js

i'm looking for a function which takes as parameters a starting and an ending date that returns an array of each first/ending days for each months in this interval.
Expected :
myFunction(new Date('2021-02-06'), new Date('2021-04-24'))
Expected output :
[
{begin: '2021-02-06', end: '2021-02-28' },
{begin: '2021-03-01', end: '2021-03-31' },
{begin: '2021-04-01', end: '2021-04-24' },
]
You can use next code:
myFunction(new Date('2021-02-06'), new Date('2021-04-24'));
function myFunction(startDateInput, endDateInput) {
var monthDifference = monthDiff(startDateInput, endDateInput)
var dates = [];
for (var i = 0; i <= monthDifference; i++) {
var month = startDateInput.getMonth();
var year = startDateInput.getFullYear();
// this gets first day in month
var startDate = new Date(year, month + i, 1)
// this gets last day in month
var endDate = new Date(year, month + i + 1, 0)
console.log('startDate', startDate);
console.log('endDate', endDate);
dates.push(
{
begin : startDate,
end : endDate
}
)
}
// this is to overwrite first and last date in array, it can be done better
dates[0].begin = startDateInput;
dates[monthDifference].end = endDateInput;
console.log('dates', dates)
}
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
Of course you can improve this code further. I made it quickly.
const formatDateString = (date) => {
const leadingZero = (d) => (100 + d + '').substr(1);
const y = date.getFullYear();
const m = leadingZero(date.getMonth() + 1);
const d = leadingZero(date.getDate());
return `${y}-${m}-${d}`;
};
const myFunction = (startIn, endIn) => {
const monthDifference = monthsDist(startIn, endIn);
const res = [];
const startYear = startIn.getFullYear();
const startMonth = startIn.getMonth();
const startDate = startIn.getDate();
for (let deltaM = 0; deltaM <= monthDifference; deltaM++) {
const monthStart = new Date(
startYear,
startMonth + deltaM,
deltaM ? 1 : startDate
);
const monthEnd =
deltaM < monthDifference ?
new Date(startYear, startMonth + deltaM + 1, 0) :
endIn;
res.push({
begin: formatDateString(monthStart),
end: formatDateString(monthEnd),
});
}
return res;
};
const monthsDist = (start, end) => {
const diffM =
(end.getFullYear() - start.getFullYear()) * 12 +
end.getMonth() -
start.getMonth();
return diffM > 0 ? diffM : 0;
};
console.log(myFunction(new Date('2021-02-06'), new Date('2021-04-24')));
console.log(myFunction(new Date('2020-02-06'), new Date('2021-04-24')));
console.log(myFunction(new Date('2021-04-06'), new Date('2021-04-24')));

Get next date(YYYY-MM-DD) according to the input date string in jQuery

Consider, I have a date that format is (Year-Month-Date),
adate = "2020-10-02";
Now I would like to create a jQuery function that input adate and return the next_date such like below,
function make_next_date(adate) {
next_date = adate + 1; //"2020-10-03"
return next_date;
}
Function should be work properly for the following input date,
adate = "2021-05-31";
next_date = "2021-06-01";
adate = "2020-12-31";
next_date = "2021-01-01";
adate = "2021-02-28";
next_date = "2021-03-01";
This is just JavaScript. JavaScript has dates. jQuery is not relevant to date manipulation.
function make_next_date(adate) {
next_date = new Date(adate);
next_date.setDate(next_date.getDate() + 1);
return next_date.toISOString().split('T')[0];
}
[
"2021-05-31",
"2020-12-31",
"2021-02-28",
].forEach(date => {
console.log({
date,
out: make_next_date(date)
});
});
function make_next_date(adate) {
const date = new Date(adate);
date.setDate(date.getDate() + 1);
// YEAR
const rYear = date.getFullYear();
// MONTH
let rMonth = date.getMonth() + 1;
rMonth = rMonth < 10 ? `0${rMonth}` : rMonth;
// DATE
let rDate = date.getDate();
rDate = rDate < 10 ? `0${rDate}` : rDate;
return `${rYear}-${rMonth}-${rDate}`;
}
["2021-05-31", "2020-12-31", "2021-02-28"].forEach((date) => {
console.log({
date,
out: make_next_date(date),
});
});
Change your string to date object.
And add 1.
Let date = new Date();
date.SetDate(Date.parseDate(your string + 1);
You can use Date class and padStart function to achieve it.
let adate = "2020-10-02";
function make_next_date(adate) {
const [year, month, day] = adate
.split("-")
.map(item => parseInt(item));
const date = new Date(year, month, day);
date.setDate(date.getDate() + 1);
return [
date.getFullYear(),
date.getMonth().toString().padStart(2, 0),
date.getDate().toString().padStart(2, 0)
].join("-")
}
console.log(make_next_date(adate));
Also, there is a very useful date manipulating package called moment. You can achieve it by just 3 lines of codes using moment.
const moment = require("moment");
const FORMAT = "YYYY-MM-DD";
let adate = "2020-10-02";
function make_next_date(adate) {
return moment(adate, FORMAT)
.add(1, "day")
.format(FORMAT);
}

How to get minutes in between two different dates?

Hi i am using Javascript and i want to get each and every minute between two dates for example:
firstDate: 2019-04-02 02:03:00
secondDate: 2019-04-03 03:04:00
So my final output result should return like this:
2019-04-02 02:03:00
2019-04-02 02:04:00
2019-04-02 02:05:00
.
.
.
2019-04-03 03:04:00
Here is the code which i tried
var boxingDay = new Date("2019-04-02 02:03:00");
var nextWeek = new Date("2019-04-03 03:04:00");
function getDatesRange(startDate, stopDate){
const ONE_DAY = 60*1000;
var days= [];
var currentDate = new Date(startDate);
while (currentDate <= stopDate) {
days.push(new Date (currentDate));
currentDate = currentDate - 1 + 1 + ONE_DAY;
}
return days.join("\n");
}
console.log(getDatesRange(boxingDay,nextWeek))
/* var map = getDates(boxingDay, nextWeek).map((times) => {
console.log(Date.parse(times))
}) */
/* console.log((getDates( boxingDay, nextWeek ))); */
The problem is I am getting correct output but I need in the form of an array, like below and reuse the function if I am reusing, it returns me an empty array.
[[2019-04-02 02:03:00],[2019-04-02 02:04:00].....]
Any solution TIA.
Using your code as a basis, you can do this as follows (note that I'm using .toISOString(), you can change this according to your needs):
const boxingDay = new Date("2019-04-02 02:03:00");
const nextWeek = new Date("2019-04-03 03:04:00");
function getDatesRange(startDate, stopDate){
const ONE_MINUTE = 60*1000;
const days= [];
let currentDate = new Date(startDate);
while (currentDate <= stopDate) {
days.push([currentDate.toISOString()]);
currentDate.setTime(currentDate.getTime() + ONE_MINUTE);
}
return days;
}
console.log(getDatesRange(boxingDay,nextWeek));
There is a way, that you could use while loop with format function, each iteration increate the minute
const firstDate = new Date('2019-04-02 02:03:00')
const secondDate = new Date('2019-04-03 03:04:00')
const formatDate = dateObj => {
const year = String(dateObj.getFullYear()).padStart(4, '0')
const month = String(dateObj.getMonth() + 1).padStart(2, '0')
const date = String(dateObj.getDate()).padStart(2, '0')
const hour = String(dateObj.getHours()).padStart(2, '0')
const minute = String(dateObj.getMinutes()).padStart(2, '0')
const second = String(dateObj.getSeconds()).padStart(2, '0')
return `${year}-${month}-${date} ${hour}:${minute}:${second}`
}
const res = []
const iteratedDate = new Date(firstDate.getTime())
while (iteratedDate <= secondDate) {
res.push(formatDate(iteratedDate))
iteratedDate.setMinutes(iteratedDate.getMinutes() + 1)
}
// res array is large so I sliced the first 10 amd the last 10
console.log(res.slice(0, 10))
console.log(res.slice(res.length - 10))
A slightly different approach using a for loop; it also avoids creating a new Date instance for each minute iterated.
const p = new Date("2019-04-02T23:57:00");
const q = new Date("2019-04-03T00:03:00");
const r = [];
for(const d = new Date(p); d <= q; d.setTime(d.getTime() + 60000))
{
r.push(d.toISOString().substring(0, 19).replace(/T/, " "));
}
const s = r.join("\n");
console.log(s);

Get a list of dates between two dates using javascript

From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this.
This is what i did.
function generateDateList(from, to) {
var getDate = function(date) { //Mysql Format
var m = date.getMonth(), d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}
var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;
if ( typeof to == 'undefined') {
end = new Date().getTime();
} else {
ts = to.split('-');
end = new Date(ts[0], ts[1], ts[2]).getTime();
}
while (start < end) {
start += 86400000;
startDate.setTime(start);
result.push(getDate(startDate));
}
return result;
}
console.log(generateDateList('2014-2-27', '2014-3-2'));
I test it from chrome and nodejs below are the result.
[ '2014-02-27',
'2014-02-28',
'2014-02-29',
'2014-02-30',
'2014-02-31',
'2014-03-01',
'2014-03-02' ]
yeh big leap year:-D..., how can i fix this? or is there any better way.?
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;
while (strDate < endDate) {
strDate = dateMove.toISOString().slice(0, 10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate() + 1);
};
Take the start date and increment it by one day until you reach the end date.
Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').
const addDays = (date, days = 1) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const dateRange = (start, end, range = []) => {
if (start > end) return range;
const next = addDays(start, 1);
return dateRange(next, end, [...range, start]);
};
const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));
console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))
Here I use a recursive function, but you could achieve the same thing using a while (see other answers).
I have used this one from
https://flaviocopes.com/how-to-get-days-between-dates-javascript/
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []
//to avoid modifying the original date
const theDate = new Date(startDate)
while (theDate < new Date(endDate)) {
dates = [...dates, new Date(theDate)]
theDate.setDate(theDate.getDate() + 1)
}
dates = [...dates, new Date(endDate)]
return dates
}
Invoke the function as follows:
getDatesBetweenDates("2021-12-28", "2021-03-01")
Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link
dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
var oDate1 = oEvent.getParameter("from"),
oDate2 = oEvent.getParameter("to");
var aDates = [];
var currentDate = oDate1;
while (currentDate <= oDate2) {
aDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:
function getDates(startDate, endDate) {
const days = [],
months = new Set(),
years = new Set()
const dateMove = new Date(startDate)
let date = startDate
while (date < endDate){
date = dateMove.toISOString().slice(0,10)
months.add(date.slice(0, 7))
years.add(date.slice(0, 4))
days.push(date)
dateMove.setDate(dateMove.getDate()+1) // increment day
}
return {years: [...years], months: [...months], days} // return arrays
}
console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
{
years: [ '2016' ],
months: [ '2016-02', '2016-03' ],
days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
}
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months
Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.

javascript check end date is greater than or equal to start date

Is it possible to check whether an end date is greater than or equal to a start date in Javascript? My dates are strings in the format 'dd/mm/yyyy'.
try this
var startDate = "05/01/2011";
var endDate = "09/01/2011";
var regExp = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/;
if(parseInt(endDate.replace(regExp, "$3$2$1")) > parseInt(startDate.replace(regExp, "$3$2$1"))){
alert("greater");
}
If the string format ('dd/mm/yyyy') doesn't change, this function should work:
function endAfterStart(start,end){
return new Date(start.split('/').reverse().join('/')) <
new Date(end.split('/').reverse().join('/'));
}
alert(endAfterStart('05/01/2011','09/01/2011')); //=> true
Or extend the Date.prototype:
Date.prototype.isBefore = Date.prototype.isBefore || function(dat){
return this < dat;
}
new Date('05/01/2011'.split('/').reverse().join('/'))
.before( new Date('09/01/2011'.split('/').reverse().join('/')) ); //=>true
Most simple way to do this.
function endAfterStart(start, end) {
var startDate = new Date(start);
var endDate = new Date(end);
return endDate.getTime() >= startDate.getTime();
}
function isDate(value)
{
var fromDate = document.getElementById("fromDate").value
var toDate= document.getElementById("toDate").value
//var curr_Date= new SimpleDateFormat("dd/mm/yyyy");
var dateRegEx = null;
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if (dateRegEx.test(fromDate)){
}
else{
alert("Invalid from date");
return false;
}
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if(dateRegEx.test(toDate)) {
}
else{
alert("Invalid to date");
return false;
}
var stDate = new Date(fromDate);
var enDate = new Date(toDate);
var compDate = enDate - stDate;
//var fdate=enDate-curr_Date;
if(compDate >= 0)
return true;
else
{
alert("To Date cannot be smaller than From Date");
return false;
}
/**/
}
This will work for Leap years also..in dd/mm/yyyy format(not any other format).
Took me some time to find, but JQuery implements this exact functionality with DatePicker date-range. (Source code available in link as well.)
Moment.js also handles date comparisons very well using the diff function.
check out this function
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
document.form1.submit();
}
}
Try this,
function isDateCompare(){
var leadDate = document.getElementById('strDate').value;
var closeDate = document.getElementById('strDateClosed').value;
var date1 = new Date();
date1.setFullYear(leadDate.substr(6,4),(leadDate.substr(3,2)-1),leadDate.substr(0,2));
var date2 = new Date();
date2.setFullYear(closeDate.substr(6,4),(closeDate.substr(3,2)-1),closeDate.substr(0,2));
if (date1> date2)
{
alert("Expected Closed date cannot be less than Lead date.");
return false;
}
else
{
alert("true");
return false;
}
}
First use this function will convert string to Date type in js:
function common_getDateFromUI(str) {
var arr = str.split("/");
var returnDate = new Date(arr[2], arr[1] - 1, arr[0], 0, 0, 0, 0);
return returnDate;
}
Second: after you get the javascript date type, you just compare it as normal type like date1 > date2 or date1 == date2.
Or use this function to get the difference date between date:
function CalendarDays(startDate, endDate) {
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.round(diff / millisecondsPerDay);
return days;
}
Follow this link is a simple demo to get difference days between dates. Link demo here
if (iForm.DiddfromDate.value == "")
{
alert(" Please enter a value");
iForm.DiddfromDate.focus();
return false;
}
if (iForm.DiddtoDate.value == "")
{
alert(" Please enter a value");
iForm.DiddtoDate.focus();
return false;
}
try {
var d1 = iForm.DiddfromDate.value.substr(0, 2);
var m1 = iForm.DiddfromDate.value.substr(3, 2);
var y1 = iForm.DiddfromDate.value.substr(6, 4);
var StrDate = m1 + "/" + d1 + "/" + y1;
var d2 = iForm.DiddtoDate.value.substr(0, 2);
var m2 = iForm.DiddtoDate.value.substr(3, 2);
var y2 = iForm.DiddtoDate.value.substr(6, 4);
var EndDate = m2 + "/" + d2 + "/" + y2;
var startDate = new Date(StrDate);
var endDate = new Date(EndDate);
if (startDate > endDate) {
alert('To date should be greater than From date.');
iForm.DiddfromDate.value = '';
iForm.DiddtoDate.value = '';
iForm.DiddfromDate.focus();
return false;
}
} catch (e) { alert(e.Description); }
return true;
Just convert the string to date and use getTime method of Date object to compare it.
Example code
var startDate = '04/04/2015'; //date in dd/mm/yyyy format
var endDate = '05/04/2015';
function compareDates(sDate, eDate) {
var dateTime1 = new Date(sDate).getTime(),
dateTime2 = new Date(eDate).getTime();
var diff = dateTime2 - dateTime1;
if (diff > 0) {
alert("endDate is greater than startDate");
return true;
}
}
compareDates(startDate, endDate);
Working Fiddle

Categories

Resources