Javascript: how to check if a timestamp belongs to the current day? - javascript

I am trying to know if a certain timestamp belongs to today, but I'm getting lost in Javascripts date management.
Is there any way to check if a timestampo belongs to the current day?

Simple check 1st timestamp of both days and compare them.
var ts = 1564398205000;
var today = new Date().setHours(0, 0, 0, 0);
var thatDay = new Date(ts).setHours(0, 0, 0, 0);
if(today === thatDay){
console.log("*** Same day ***");
}

It seems nasty-ish to me however you could do something similar to:
function isInToday(inputDate)
{
var today = new Date();
if(today.setHours(0,0,0,0) == inputDate.setHours(0,0,0,0){ return true; }
else { return false; }
}
This assumes you've already set your input date as a JS date. This will check if the two dates occur on the same day, and return true if so and false if not.
I'm sure someone will come along with a neater way to do this or a case where this fails but as far as I can see this should do the trick for you.

you can really depend on ISO date string with a substr function to compare the two strings
var T=1479288780873; /*assume your timestamp value*/
var theDay=new Date(T);
var today=new Date;
theDay.toISOString().substr(0,10) == today.toISOString().substr(0,10) ? console.log("same day"):null;

You can do something like this :
var day = 24 * 60 * 60 * 1000; //nb millis in a day
var todayTimestamp = new Date(year, month, day).getTime(); // Be careful month is 0 start
//OR
var todayTimestamp = new Date().setHours(0,0,0,0).getTime();
var diff = myTimestamp - todayTimestamp;
if ( diff >= 0 && diff <= day ) {
console.log("timestamp is today");
else {
console.log("timestamp is not today");
}

var timestamp = '2016-11-16 03:14:07.999999';
var datestamp = timestamp.substring(0, 10);
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(), mm, dd].join('-');
};
var date = new Date();
date.yyyymmdd();
console.log(String(datestamp) === String(date.yyyymmdd()));

It depends what format your timestamp is in.
But here is the most basic way to achieve this:
var today = new Date(year, month, day);
var timestamp = //your timestamp;
if (timestamp == timestamp){ //make sure the date formats are the same
//your code
}
I hope this is what you were looking for, there are more methods with the javascript date reference, don't hesitate to look it up.

Related

Only show data on html page where javascript date is within last 10 days

I have javascript array in which the date coming in is in this format
2015-11-25T17:54:19.033
However, I am not really concerned with the time
so I end up with
11/25/15
What I want to do in my loop is to LOOK at the date ( either 2015-11-25T17:54:19.033 or 11/25/15 , whatever is easier) and just set a variable to "NEW" if it is within the last 10 days
I was attempted to play around with this code and it does not give me what I want at all
var dt = "11/25/15";
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-10)
console.log(dt);
console.log(today);
console.log(priorDate);
pseudo code of what i WANT
if ( dt <= today ) {
x = "NEW";
}
So my thoughts are that it need to be in Date objects in javascript but i'm not sure
Update
So say in a loop i have these variables that occur
for ....
dt = 9/13/15
Output = 9/13/15
next time in loop
dt = 11/24/15
Output = NEW - 11/24/15
Working jsfiddle
http://jsfiddle.net/bthorn/yr009hwd/
You are correct. You need to convert the string date to a date time object in javascript to do the comparison.In order to do the comparison, you need to get the millisec of the dates using getTime()
var dt = new Date("11/22/2015");
var today = new Date();
if ( dt.getTime() < today.getTime() ) {
alert('Past');
}
else
alert('future');
To check if the date difference is within 10 days:
var dt = new Date("11/12/2015");
var today = new Date();
var dateDiffDays = Math.ceil((Math.ceil(dt.getTime() - today.getTime()))/(1000 * 3600 * 24));
if( dateDiffDays >= -10 && dateDiffDays <= 10)
alert('date within 10 days');
Depending on the format of your date string, you can probably just do:
var dateToTest = new Date(dt);
//get 10 days earlier
dateToTest.setDate(dateToTest.getDate() - 10);
var today = new Date();
if ( dateToTest < today ) {
x = 'NEW';
}
//see if a date is within the last 10 days
var tenDaysAgo = new Date(); //current date
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10); //ten days ago
//if you don't care about the time
tenDaysAgo.setHours(0);
tenDaysAgo.setMinutes(0);
tenDaysAgo.setSeconds(0);
tenDaysAgo.setMilliseconds(0);
var someDateToTest = new Date('11-1-2015');
if (tenDaysAgo > someDateToTest) {
//this is new
x = 'NEW';
}

comparing dates in JavaScript using moment with langs

I have two dates namely newdate and haha. newdate will be today's date (current date) and haha date can be any.The below code is not working for me as i have provided
newdate : 07-Feb-2014 10:04
haha :03-Feb-2014 00:00
its always coming to else part
sdate:03-Feb-2014
stime :00:00
var haha=sdate+" "+stime;
var newdate=new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
}
else {
alert("hahahhahaha");
}
NOTE I am using moment with langs javscript
Your Code Works. Stime is formatted wrong remove the colon from in front of the first set of 00. stime 00:00. How are you generating stime this is the cause of you problem?
You can see my test here.
var sdate = "03-Feb-2014";
var stime = "00:00";
var haha = sdate + " " + stime;
var newdate = new Date();
if (navigator.appName.indexOf("Internet Explorer") != -1) {
alert("isIE");
var dateObject = (parseISO8601(haha));
var hahaDate = new Date(dateObject.year, dateObject.month, dateObject.day, dateObject.hour, dateObject.min);
alert(hahaDate);
if (hahaDate.getTime() < newdate.getTime()) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
} else {
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
}
function parseISO8601(dateStringInRange) {
var dateAsObject = {};
var splitTimeFromDate = dateStringInRange.split(" ");
var splitTimeValues = splitTimeFromDate[1].split(":");
dateAsObject.hour = splitTimeValues[0];
dateAsObject.min = splitTimeValues[1];
var splitDate = splitTimeFromDate[0].split("-");
dateAsObject.year = splitDate[2];
dateAsObject.day = splitDate[0];
dateAsObject.month = monthToNum(splitDate[1]);
return dateAsObject;
}
function monthToNum(month) {
if (month == "Feb") return 1;
}
[Edit: Ok sorry I messed up with the Colon, If it fails at the else are you sure you unit tests include enough scenario to were the date is both greater than and less than the current date if it is only less than like your example you will never hit the code in the else. Again the code just works don't know what to say :-(, update example for both situations]
[Edit: Here is an example not complete you have to remember javascript is not universal. When you ask a question about JS assume as DEVs we all use Chrome or FF, or atleast post the browser(s) you tired. I provided a simple example of how I would accomplish this. Frankly I don't like external framework when I can do it myself so as you can see I am not using it feel free to do what you want the issue is cause by the way IE Parses DateTime you must use a more universal format like the one provided below. Example of possible formats: http://www.w3schools.com/jsref/jsref_obj_date.asp. Anyhow GL]
That is a bit convoluted, consider:
var newdate = new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
Date.parse(date_str);
if the above works (and there is absolutely no guarantee that Date.parse will correctly parse the string in all browsers in use), then all of that is equivalent to:
var newdate = new Date();
newdate.setSeconds(0, 0);
You would do very much better to manualy parse haha (or use moment.js since you have it already) and compare the resultant date objects.
Consider:
// s is dd-mmm-yyyy hh:mm
function stringToDate(s) {
s = s.split(/[- :]/);
var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun': 5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
return new Date(s[2], months[s[1].toLowerCase()], s[0], s[3], s[4], 0, 0);
}
var newdate = '07-Feb-2014 10:04';
var haha = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // false
// Set to same time
var newdate = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // true

Check if a date within in range

I am trying to check if a date of format mm.dd.yyyy is greater than today and less than the date after 6 months from today.
Here is my code:
var isLinkExpiryDateWithinRange = function(value) {
var monthfield = value.split('.')[0];
var dayfield = value.split('.')[1];
var yearfield = value.split('.')[2];
var inputDate = new Date(yearfield, monthfield - 1, dayfield);
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
alert(inputDate > today);//alert-> true
var endDate = today;
endDate.setMonth(endDate.getMonth() + 6);
alert(inputDate > today);//alert-> false
if(inputDate > today && inputDate < endDate) {
alert('1');
} else {
alert('2');/always alert it
}
}
If I execute isLinkExpiryDateWithinRange('12.08.2012') I wish it will show 1 as this is within the range, but it is displaying 2. Moreover the first alert is showing true and the second one false.
Can anyone please explain what is happening?
Change:
var endDate = today;
to:
var endDate = new Date(today);
See the posts here for how objects are referenced and changed. There are some really good examples that help explain the issue, notably:
Instead, the situation is that the item passed in is passed by value.
But the item that is passed by value is itself a reference.
JSFiddle example
function isLinkExpiryDateWithinRange( value ) {
// format: mm.dd.yyyy;
value = value.split(".");
var todayDate = new Date(),
endDate = new Date( todayDate.getFullYear(), todayDate.getMonth() + 6, todayDate.getDate() +1 );
date = new Date(value[2], value[0]-1, value[1]);
return todayDate < date && date < endDate;
}
isLinkExpiryDateWithinRange("12.24.2012"); // true
isLinkExpiryDateWithinRange("12.24.2020"); // false
Below function checks if date selected is within 5 days from today. Date format used is "DD-MM-YYYY", you can use any format by changing value.split('-')[1] order and split character.
function showMessage() {
var value = document.getElementById("invoiceDueDate").value;
var inputDate = new Date(value.split('-')[2], value.split('-')[1] - 1, value.split('-')[0]);
var endDate = new Date();
endDate.setDate(endDate.getDate() + 5);// adding 5 days from today
if(inputDate < endDate) {
alert("If the due date selected for the invoice is within 5 days, and express settlement fee will apply to this transaction.");
}
}

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

how to compare only time in javascript?

I want to compare only time on client side, means the start time should not be greater than end time. I have searched on net but not able resolve this problem. Please help me as soon as possible. Thanks in advance.
you can compare date in javascript
check following code
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}
For example lets say the time picked for example
var startTime = "09:15";
var endTime ="10:15";
if(parseInt(startTime.split(":")[0],10) > parseInt(endTime.split(":")[0],10))
alert("Start Time should not be greater than end time");
else
alert("Valid Time");
Hope this helps.
You'll need to use the Date object functions to pull out the hours minutes and seconds to get just the time from a Date:
var currentDate = new Date();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
Using DateJS you can use the following method compareTo
var past = Date.today().add(-6).days();
var future = Date.today().add(6).days();
Date.today().compareTo(future); // -1
Date.today().compareTo(new Date().clearTime()); // 0
Date.today().compareTo(past); // 1
if you do not want to use a whole library here is the source code for the static compare method in DateJS
Date.compare = function (date1, date2) {
if (isNaN(date1) || isNaN(date2)) {
throw new Error(date1 + " - " + date2);
} else if (date1 instanceof Date && date2 instanceof Date) {
return (date1 < date2) ? -1 : (date1 > date2) ? 1 : 0;
} else {
throw new TypeError(date1 + " - " + date2);
}
};
This will work for time as well asuming that both dates (yyyy-MM-dd) are the same

Categories

Resources