how to compare only time in javascript? - 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

Related

How to convert user timezone to UTC?

I'm using the TimeIt code on my site, it can be found here: http://codegen.in/timeit/
This is the direct link to the code: https://res.cloudinary.com/vsevolodts/raw/upload/v1503371762/timeit.min.js
It looks like this:
//version 3. 2017-08-13
function timeit() {
var next_run_array = []; //array of dates/time on a page used to rerun function if a change should happen during the session
var curDate = new Date();
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(),
(mm > 9 ? '' : '0') + mm,
(dd > 9 ? '' : '0') + dd
].join('-');
};
var curDateYMD = curDate.yyyymmdd();
$('.timeit').each(function() {
var end = $(this).data('end'),
start = $(this).data('start');
//check if date or time value has valid format and push it to the list of refresh anchors
var startDate = checkdate(start, this);
var endDate = checkdate(end, this);
nextrun(startDate);
nextrun(endDate);
//add a datetime when the page needs to be refreshed (now+24 hrs time span only)
function nextrun(date) {
var nextruntimeout = date - curDate;
if (nextruntimeout < 1000 * 60 * 60 * 24 && nextruntimeout > 1000) {
next_run_array.push(nextruntimeout);
}
}
// Main Function
//check if the evend outside of a desired time span
if (((startDate < endDate) && (startDate > curDate || endDate < curDate)) ||
((startDate > endDate) && (startDate >= curDate) && (endDate <= curDate))
) {
$(this).addClass('hidden');
} else {
$(this).removeClass('hidden');
}
//Support Functions
//correct data creation from a string. accepted format YYYY-MM-DD HH:MM
function parseISO8601(d) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)?.(\d\d)?.(\d\d)\s*$/,
date = new Date(NaN),
datenew,
month,
dateString=d.substr(0, d.indexOf(' '));
parts = isoExp.exec(d);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
date = new Date(parts[1], month - 1, parts[3], parts[4], parts[5])
}
return date;
}
//unification of the date string to the format YYYY-MM-DD HH:MM
function checkdate(date, obj) {
if (date) {
//check if only time is set (HH:MM); if so, add today's date
if (String(date).length < 6 && String(date).indexOf(":") > -1) {
date = curDateYMD + ' ' + String(date);
}
//check if only date is set; if so add 00:00 to the end of date
if (String(date).indexOf(":") == -1) {
date = date + ' 00:00';
}
//check if date is valid (avoid valid time)
var res = date.split(":"),
h = String(res.slice(0, 1)),
hours = h.substr(h.length - 2),
minutes = res.slice(1);
var timetest = (hours < 24 && minutes < 60) ? true : false;
//check if date is could be created from a value; if fails try to parse a string to a format
var returndate = new Date(date);
if (returndate == 'Invalid Date') {
var returndate = parseISO8601(date);
};
if (returndate == 'Invalid Date' || !timetest) {
//highlight the element if the is an error. use own \.error class if needed
$(obj).addClass("error").attr('title', '"' + date + '" date is incorrect; please use YYYY-MM-DD HH:MM format');
}
return returndate.getTime();
} else {
//if datetime is not set, just return current date-time
return curDate.getTime();
}
}
});
/* Schedule next runs */
if (next_run_array.length > 0) {
var nextruntime = Math.min.apply(null, next_run_array);
console.log("next run of timeit function is in " + nextruntime / 1000 + "seconds");
setTimeout(function() {
timeit();
}, nextruntime);
}
}
timeit();
(
Then you just put the embed code:
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between 2019-02-15 - 2019-07-25
</div>...<script src="/js/timeit.js"></script>
The idea is: my content is being shown between a certain period of time. I would like it to work with the UTC time zone, but right now the code is getting the date/hour info from the user's local time zone. So my content becomes available for example not at 8 AM UTC, but at 8 AM of the user's local time zone. I would like to change that.
I really, really tried to work this out on my own, but I guess this is beyond my skill set (which is pretty low). I'm confused by all the info about those ISO 8601, new Date, Date, I can't really find where it says "get the time from this source" to replace it with "get it from UTC". So - if any of you would just take a look at it and tell me what to put where, I would be extremely grateful.
Thank you all for your time!
Since you can't use server-side scripting because of Weebly... You will have to rely on the client's clock which can be tweeked. And the hidden class can easily be removed... But it seems you don't have the choice.
Now, I will suggest you to forget about the TimeIT plugin.
When it comes to dates in JavaScript/jQuery, I always recommand the use of moment.js which is really easy to use (you won't have to perform complex caluculations anymore) and fully documented, so you can do whatever you wish.
Here, content hiding based on start/end dates in data attributes would look like this:
$(document).ready(function(){
var utc_date = moment().utc().format("YYYY-MM-DD HH:mm"); // Client's date/time in UTC
$(".timeit").each(function(){
var start = moment($(this).data("start")).format("YYYY-MM-DD HH:mm");
var end = moment($(this).data("end")).format("YYYY-MM-DD HH:mm");
console.log((utc_date>start && utc_date<end)?"Content displayed":"Content hidden");
$(this).addClass("hidden"); // Hide content by default
if(utc_date>start && utc_date<end){
$(this).removeClass("hidden"); // Show content if now is between start/end dates
}
});
}); // ready
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between the dates in data attributes
</div>
You can try it in CodePen... Change the start date and hit "Run". I left some console logs so you can understand what is going on.
For more, explore moment.js documentation.

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

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.

How to check if date is in this week in javascript?

I have this date "2016-04-23T11:45:00Z" and I want to check this date in this week or not ?
Thanks,
Dates are hard, I would always suggest using a library dedicated to date handling as it reduces the chances of errors in your code.
MomentJS is a good one.
var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())
Edit: Please note as of 2020 moment may not be a good choice for new projects
This seems to be working for me.
function isDateInThisWeek(date) {
const todayObj = new Date();
const todayDate = todayObj.getDate();
const todayDay = todayObj.getDay();
// get first date of week
const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));
// get last date of week
const lastDayOfWeek = new Date(firstDayOfWeek);
lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);
// if date is equal or within the first and last dates of the week
return date >= firstDayOfWeek && date <= lastDayOfWeek;
}
const date = new Date();
const isInWeek = isDateInThisWeek(date);
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">
<h1>{{currentDate}}</h1>
<h1>{{numberCurrentDateWeeks}}</h1>
<h1>{{yourDate}}</h1>
<h1>{{numberYourDateWeeks}}</h1>
</div>
</div>
......
angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
s.yourDate = '2016-04-23T11:45:00Z'
s.currentDate = new Date();
s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");
}]);
then you got the Week numbers just compare or do whatever you like
cheers !
You can do that without any libraries by checking if the date.getTime() (milliseconds since epoch) is between last monday and next monday:
const WEEK_LENGTH = 604800000;
function onCurrentWeek(date) {
var lastMonday = new Date(); // Creating new date object for today
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
const res = lastMonday.getTime() <= date.getTime() &&
date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
return res; // true / false
}
(one week in ms = 24 * 60 * 60 * 1000 * 7 = 604,800,000)
May not be the most optimal solution, but I think it's quite readable:
function isThisWeek (date) {
const now = new Date();
const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
const monthDay = now.getDate();
const mondayThisWeek = monthDay - weekDay;
const startOfThisWeek = new Date(+now);
startOfThisWeek.setDate(mondayThisWeek);
startOfThisWeek.setHours(0, 0, 0, 0);
const startOfNextWeek = new Date(+startOfThisWeek);
startOfNextWeek.setDate(mondayThisWeek + 7);
return date >= startOfThisWeek && date < startOfNextWeek;
}
This link explaines, how to do this without using any js libraries. https://gist.github.com/dblock/1081513
Code against link death:
function( d ) {
// Create a copy of this date object
var target = new Date(d.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (d.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week
// with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
var weekNr = 1 + Math.ceil(dayDiff / 7);
return weekNr;
}
I managed to do it with this simple trick and without any external library.
Considering monday as the first day of the week, the function takes as parameter a date string and do the validation before checking if the day indeed is in the current week.
function isInThisWeek(livr){
const WEEK = new Date()
// convert delivery date to Date instance
const DATEREF = new Date(livr)
// Check if date instance is in valid format (depends on the function arg)
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
In the comments I saw that you stated that your week starts on Monday.
In that case, I guess it'd be a good idea to calculate the ISO week number of the 2 dates and see if you get the same week number for both of them.
To calculate the ISO week number, check this answer:
In case anyone else's week starts on Sunday instead, you can use this answer to calculate the week number accordingly.
then you can do something like this:
function isSameWeek(date1, date2) {
return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
const today = new Date();
//Get the first day of the current week (Sunday)
const firstDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay())
);
//Get the last day of the current week (Saturday)
const lastDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay() + 6)
);
//check if my value is between a minimum date and a maximum date
if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
return true;
} else {
return false;
}
};

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

Determine if a date is a Saturday or a Sunday using JavaScript

Is it possible to determine if a date is a Saturday or Sunday using JavaScript?
Do you have the code for this?
Sure it is! The Date class has a function called getDay() which returns a integer between 0 and 6 (0 being Sunday, 6 being Saturday). So, in order to see if today is during the weekend:
var today = new Date();
if(today.getDay() == 6 || today.getDay() == 0) alert('Weekend!');
In order to see if an arbitrary date is a weekend day, you can use the following:
var myDate = new Date();
myDate.setFullYear(2009);
myDate.setMonth(7);
myDate.setDate(25);
if(myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
You can simplify #Andrew Moore 's test even further:
if(!(myDate.getDay() % 6)) alert('Weekend!');
(Love that modulo function!)
The Date class offers the getDay() Method that retrieves the day of the week component of the date as a number from 0 to 6 (0=Sunday, 1=Monday, etc)
var date = new Date();
switch(date.getDay()){
case 0: alert("sunday!"); break;
case 6: alert("saturday!"); break;
default: alert("any other week day");
}
I think this is an elegant way to do this:
function showDay(d) {
return ["weekday", "weekend"][parseInt(d.getDay() / 6)];
}
console.log(showDay(new Date()));
Yes, it is possible, we can write a JavaScript code for that using JavaScript Date object.
Please use following JavaScript code.
var d = new Date()
document.write(d.getDay())
We can write a function to return the weekend in flag like below,
You can more customize the function to pass date. Or different return values for every day.
isItWeekEnd = function() {
var d = new Date();
console.log(d.getDay());
var dateValue = d.getDay();
// dateValue : 0 = Sunday
// dateValue : 6 = Saturday
if(dateValue == 0 || dateValue == 6)
return true;
else
return false;
}
var date = new Date();
var day = date.getDay();
if(day==0){
return false;
//alert('sunday');
}

Categories

Resources