Javascript if the first datetime is greater than the second datetime - javascript

JAVASCRIPT
I have looked at a number of questions concerning how this is done but none of them work with my code. I am trying to findout if the "nowdate" is less than "startdate". The code below is what I have so far:
INPUT :
Start date: 01-03-2019 00:00
End date: 31-03-2019 23:59
My code;
var nowdate;
var d = new Date();
nowdate = ('0' + d.getDate()).slice(-2) + "-" + ('0' + (d.getMonth() + 1)).slice(-2) + "-" + d.getFullYear() + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2);
This produces : Now date: 17-02-2019 16:43
if(nowdate < startdate){
console.log("Start date is greater than now date");
} else {
console.log("Start date is NOT greater than now date")
}
This does not produce the result I am expecting. Can anyone see why.
Many thanks in advance for your help and time.

You should use Date.prototype.getTime() when you want to compare two dates
let startDate = (new Date('01-03-2019 00:00')).getTime()
let nowDate = (new Date()).getTime();
if(nowDate < startDate){
console.log("Start date is greater than now date");
}
else{
console.log("Start date is NOT greater than now date")
}

Related

Date not displaying properly in JS dates app

I am trying to make a simple JS calendar which will indicate the current date and then 90 dates after this date. I want it to be displayed as, example: Monday, May 6, 2019 -and- Sunday August 4, 2019. Can you tell me why my second date is displaying differently? Thank you! (I've attached the html file with the code).
I am able to set both dates to display like: 05/06/2019 and 08/04/2019, but when I attempt to change and use the arrays to display to the above syntax, the second date does not display correctly.
I have created a JS Fiddle that shows the code and the result, here:
https://jsfiddle.net/Catja_M/68q0s7fy/2/
var now = new Date();
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;}
today=days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear()));
document.write(today);
var now = new Date();
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var months = new
Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;}
var today=new Date()
new Date(days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())));
today.setDate(today.getDate()+90)
document.write(today);
Looking to achieve both dates to display the same: Monday, May 6, 2019.
change this:
var today=new Date()
new Date(days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())));
today.setDate(today.getDate()+90)
document.write(today);
to:
now.setDate(now.getDate() + 90) //this returns a total millis number not a "date", it needs to be converted to day/month/year
var date = ((now.getDate()<10) ? "0" : "") + now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
var today = days[now.getDay()] + ", " + months[now.getMonth()] + " " + date + ", " + fourdigits(now.getYear());
document.write(today);

Comparing a start datetime and end datetime from php with a date in Javascript

after reading many question here relating to this subject I am still having issues resloving my problem.
I am having issues with comparing dates-times in JavaScript. I am reading the "startdate" and "enddate" from a data table where there are two records.
I am using the line below to create my "nowdate":
nowdate = ('0' + (d.getMonth() + 1)).slice(-2) + "-" +('0' + d.getDate()).slice(-2) + "-" + d.getFullYear() + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2);
This gives me:
Now date: 03-01-2019 11:28
Start date: 03-01-2019 23:59
End date : 03-08-2019 23:59
Now date: 03-01-2019 11:28
Start date: 04-01-2019 23:59
End date: 04-30-2019 23:59
I then need to know if the "startdate" and "enddate" are between "Now date".
if (new Date(startdate) >= new Date(nowdate) && new Date(nowdate) <= new Date(enddate)) {
console.log("Active: ");
} else if (new Date(nowdate) < new Date(enddate)) {
console.log("Scheduled: ");
} else {
console.log("Complete: ");
}
EDITED CODE:
// RECORD 1
MOMENT NOW DATE: 03-01-2019 14:03
MOMENT START DATE: 03-01-2019 23:03
MOMENT END DATE: 03-08-2019 23:03
// RECORD 2
MOMENT NOW DATE: 03-01-2019 14:03
MOMENT START DATE: 04-01-2019 23:04
MOMENT END DATE: 04-30-2019 23:04
var nowdate;
var d = new Date();
nowdate = (d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2)) + "-" + ('0' + d.getDate()).slice(-2) + " " + ('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2);
nowdate = moment(nowdate).format('MM-DD-YYYY HH:MM');
var startdate2 = moment(startdate2).format('MM-DD-YYYY HH:MM');
var enddate2 = moment(enddate2).format('MM-DD-YYYY HH:MM');
console.log("MOMENT NOW DATE: ", nowdate);
console.log("MOMENT START DATE: ", startdate2);
console.log("MOMENT END DATE: ", enddate2);
if (startdate2 >= nowdate || enddate2 <= nowdate) {
console.log("Active: ");
}
else if (startdate2 > nowdate) {
console.log("Scheduled: ");
}
The issue I have is both records are show as "Active". Can antone see where I have gone wrong.
Many thanks in advance for your help and time.
As others have stated, you have to provide a valid date format string, if using new Date() this way. You can either parse your string for date parts and construct it:
const dt = new Date(2019, 2, 1, 11, 28); // months are 0 index based
Or, you can use something like MomentJs or Luxon to parse your dates, and then do your diff check. Moment is going to give you the greatest flexibility to provide your own format to parse against.
For instance, you can use Moment to properly parse a date string in nearly any format, by providing the format to Moment. Say you have your current date string, from your backend, as 03-01-2019 14:03. Using Moment, you parse this via const sd = moment('03-01-2019 14:03', 'MM-DD-YYYY HH:mm'). Get the current date, with Moment, via const now = moment(). Then compare sd > now.

current time in hh:mm:ss tt formate in javascript

I'm currently doing a web based task. I've got current time in this format.
hh:mm:ss
var currentdate = new Date();
var datetime =
currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
document.write(datetime);
How can i get current time in this format:
hh:mm:ss tt
Where tt is milliseconds. [i.e., 09:46:17 89]
Do something like this:
var date = new Date();
var milliSeconds = date.getMilliseconds();
You can add milliseconds to your function, but remember, for milliseconds format must be
hh:mm:ss ttt
If you only want two units of milliseconds, you must make a rounding
var currentdate = new Date();
var datetime =
currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds() + " "
+ currentdate.getMilliseconds();
document.write(datetime);
Try this by using the getMilliSeconds() method:
var currentdate = new Date();
var datetime =
currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds() + " "
+ Math.floor(currentdate.getMilliseconds() / 10).toFixed(0) ;
document.write(datetime);
The Math.floor(currentdate.getMilliseconds() / 10).toFixed(0) will make sure that you are getting the millisecond in 2 digit format as expected i.e, tt

Splitting a date using javascript

I am trying to split a date using the following piece of JavaScript
var dSplit = getDate.split("/");
var newDate = dSplit[2] + "-" + dSplit[0] + "-" + dSplit[1];
I get the following output
2014 12:00:00 AM-11-25
The output i require is
2014-11-25 12:00:00 AM
Please Help.
One possible approach:
var getDate = '11/25/2014 12:00:00 AM';
var newDate = getDate.replace(/^\S+/, function(date) {
var d = date.split('/');
return d[2] + '-' + d[0] + '-' + d[1];
});
// 2014-11-25 12:00:00 AM
This approach allows to process both datetime strings (similar to '11/25/2014 12:00:00 AM', like in your answer) and date strings (like '11/25/2014'). The key here is processing only first sequence of non-whitespace characters in the string.
You may format the date to string as you want, using the next function:
function formatDate(date) {
var ans = date.getFullYear();
ans += "-" + (date.getMonth()+1);
ans += "-" + date.getDay();
ans += " " + date.getHours();
ans += ":" + date.getMinutes();
document.write (ans);
}
This way, even if the user's browser converts date to string on different order (longer format etc.) you have full control on the output string.
This may be helpfull,pass$val alone in function
var dateString=$val.split(" ");
var dateformat=dateString[0].split("-");
var dateVal= dateformat[0] + "/" + dateformat[1] + "/" + dateformat[2];
$.date = function(dateObject) {
var d = new Date(dateObject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = year + "-" + month + "-" + day;
return date;
};

Get date using javascript in this format [MM/DD/YY]

how can I get the date in this format [mm/dd/yy] using javascript. I am struggling to get the 'year' to a 2 digit figure as opposed to the full 4 digits. Thanks!
var date = new Date();
var datestring = ("0" + (date.getMonth() + 1).toString()).substr(-2) + "/" + ("0" + date.getDate().toString()).substr(-2) + "/" + (date.getFullYear().toString()).substr(2);
This guarantees 2 digit dates and months.
Try this:
HTML
<div id="output"></div>
JS
(function () {
// Get current date
var date = new Date();
// Format day/month/year to two digits
var formattedDate = ('0' + date.getDate()).slice(-2);
var formattedMonth = ('0' + (date.getMonth() + 1)).slice(-2);
var formattedYear = date.getFullYear().toString().substr(2,2);
// Combine and format date string
var dateString = formattedMonth + '/' + formattedDate + '/' + formattedYear;
// Reference output DIV
var output = document.querySelector('#output');
// Output dateString
output.innerHTML = dateString;
})();
Fiddle: http://jsfiddle.net/kboucher/4mLe1Lrd/
How About this for the year
String(new Date().getFullYear()).substr(2)
And since you need your Month from 01 through 12 do this
var d = new Date("2013/8/3");
(d.getMonth() < 10 ? "0" : "") + (d.getMonth() + 1)
Do the same thing for days, Minutes and seconds
Working Demo

Categories