add class if date is today - javascript

I have some boxes that represent the squares in an advent calendar. I've defined the date for each box in the data attribute which I'm using to compare against the current day. I'm trying to add a class 'today' to the box that represents the current day. I've created a fiddle to demonstrate this. How can I fix it so that today class is added to the appropriate box?
JSFiddle
$(function() {
var currentDate = Date.now();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
if (!isNaN(date) == currentDate) {
$(this).addClass('today');
}
else if(!isNaN(date) && currentDate - date > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});

You don't have to use Date.now() as this doesn't outputs the dates similar to the data attributes have. Instead you have to create current date as this and check in the conditions like:
$(function() {
var date = new Date(),
currentDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
if (specifiedDate == currentDate) {
$(this).addClass('today');
} else if (currentDate > specifiedDate) {
$(this).addClass('past');
} else {
$(this).addClass('future');
}
});
});
.grid-item {
height: 170px;
width: 170px;
float: left;
background: red;
margin: 10px;
}
.today {
background: yellow;
border: red 1px solid;
}
.past {
background: black;
border: red 1px solid;
}
.future {
background: blue;
border: red 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item" data-date="2015-11-23">
</div>
<div class="grid-item" data-date="2015-11-24">
</div>
<div class="grid-item" data-date="2015-11-25">
</div>
<div class="grid-item" data-date="2015-11-26">
</div>
<div class="grid-item" data-date="2015-11-27">
</div>
<div class="grid-item" data-date="2015-11-28">
</div>
<div class="grid-item" data-date="2015-11-29">
</div>

You can add class to current date using following jquery, just replace your jquery with following :-
$(function() {
var d =new Date();
var curmonth = d.getMonth()+1;
var curDate = d.getFullYear()+"-"+curmonth+"-"+d.getDate();
$(".grid-item[data-date="+curDate+"]").addClass("today");
});

A possible solution
jsfiddle
$(function() {
var currentDate = Date.now();
var a = new Date(currentDate);
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
var b = new Date(date);
if (!isNaN(b) && b.getMonth() == a.getMonth() && b.getDay()== a.getDay() && b.getYear() == a.getYear()) {
$(this).addClass('today');
}
else if(!isNaN(b) && a - b > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});

See this JSFiddle
JavaScript
$(function() {
var currentDate = Date.parse((new Date()).toLocaleDateString());
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
if (!isNaN(date) && date == currentDate) {
$(this).addClass('today');
}
else if(!isNaN(date) && currentDate - date > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});

There is a single mistake in your code. Date.now() gives you the current timestamp in milliseconds. While you have a date in the data-date which will not match in any case. Correct way will be to compare the date instead of timestamps. Or just take the date without the time for comparison

The easiest solution would be to create new Date() object, and set it's hours, minutes and seconds to 0 like that:
currentDate = new Date();
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
and then:
var date = new Date(specifiedDate);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
Note that I am also setting date's hours, minutes and second to 0 due timezones (this can be fixed, but as I said, it seems to be the easiest way)

Or you can simply use :
$(function() {
$(".grid-item").each(function() {
$('.grid-item').eq(new Date().getDay()-1).addClass('today');
});
});
FIDDLE

Try This code
$(function() {
var currentDate = new Date();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = new Date(specifiedDate);
if(date.setHours(0,0,0,0) == currentDate.setHours(0,0,0,0)){
$(this).addClass('today');
}
});
});

this code works for me last day. hope this helps you..
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = yyyy+'-'+mm+'-'+dd;
if (date == today) {
$(this).addClass('today');
}
make sure two dates are same format..

Related

v-calendar does not highlight dates inside props when selected

I'm trying to highlight my vue calendar based on start and end dates that I select. I am following the documentation but it doesn't seem to provide much detail on how to select dates https://vcalendar.io/attributes.html
currently I am able to select dates and store them into my state using the dayClicked method but when I use the dates prop inside attributes to set the highlighted days nothing happens. I have noticed that if I just
replace
dates: { start: new Date(year, month, this.selectedDay.day), end: new Date(year, month, this.endDate.day)},
with
dates: { start: new Date(year, month, 12), end: new Date(year, month, 14)},
it works fine, but I have checked to make sure the values being passed are integers so I'm assuming it just doesn't have access to data() for some reason... I'm hoping someone can help me find a way around this problem and pass my days to the calendar component somehow
Any help is appreciated :)
<template>
<div id="calendarContainer">
<DatePicker is-range :attributes='attributes'
#dayclick='dayClicked'
/>
<button class="arrowBtnsLeft" #click="monthBack"><</button>
<button class="arrowBtnsRight" #click="monthForward">></button>
</div>
</template>
<script>
import DatePicker from 'v-calendar/lib/components/calendar.umd'
export default {
name: 'calendar',
components:{
DatePicker,
},
data() {
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()
return {
selectedDay: {day: 14},
endDate: {day: 17},
attributes: [
// This is a single attribute
{
key: 'today',
highlight:{
start: {fillMode: 'outline'},
end: {fillMode: 'outline'},
color:'red',
fillMod:'light'
},
dates: { start: new Date(year, month, this.selectedDay.day), end: new Date(year, month, this.endDate.day)},
}
]
}
},
onMounted(){
console.log(this.range)
},
methods: {
dayClicked(day) {
if(this.selectedDay == null){
this.selectedDay = day;
//change days styles to be blue
}else if(this.selectedDay!== null && this.endDate == null){
this.endDate = day;
//change days styles to be blue
//change days days inbetween to be outlined
console.log('start',this.selectedDay, 'end', this.endDate)
this.selectedDay.classes.push('start')
this.endDate.classes.push('end')
}else{
//remove classes for start and end
this.selectedDay.classes.pop()
this.endDate.classes.pop()
this.selectedDay = day;
this.endDate = null;
}
},
monthForward(){
let newtime = this.context.selectedYMD.split('-')
var timestring = ''
newtime[1] = parseInt(newtime[1])+1
newtime[1] = newtime[1].toString()
for( let i = 0; i < 3; i ++){
console.log(newtime[i])
if(i < 2){
timestring+=newtime[i]+'-'
}else{
timestring+=newtime[i]
}
}
this.value = timestring
},
monthBack(){
let newtime = this.context.selectedYMD.split('-')
var timestring = ''
newtime[1] = parseInt(newtime[1])-1
newtime[1] = newtime[1].toString()
for( let i = 0; i < 3; i ++){
console.log(newtime[i])
if(i < 2){
timestring+=newtime[i]+'-'
}else{
timestring+=newtime[i]
}
}
this.value = timestring
}
}
}
</script>
<style>
#calendarContainer{
position: relative;
z-index: 1;
width: 50%;
height: 50%;
}
.inTrip{
border-top:1px solid gray;
border-bottom:1px solid gray;
}
.start{
border-radius: 20px;
border-left:1px solid gray;
border-right:none;
background-color:#2E9CFF;
color:white;
}
.end{
border-radius: 20px;
border-right:1px solid gray;
border-left:none;
background-color:#2E9CFF;
color:white;
}
.arrowBtnsLeft{
position:absolute;
top:.8em;
left:12em;
background-color:#afd7f78e;
color:#2E9CFF;
border: none;
margin-left: .5em;
margin-right: .5em;
border-radius:5px;
text-align: center;
}
.arrowBtnsRight{
position:absolute;
top:.8em;
left:14em;
background-color:#afd7f78e;
color:#2E9CFF;
border: none;
margin-left: .5em;
margin-right: .5em;
border-radius:5px;
text-align: center;
}
</style>
if anyone is curious I found a solution, I used the computed properties to return 2 sets of days
<template>
<div id="calendarContainer">
<Calendar :attributes='attr' #dayclick='onDayClick' />
<button class="arrowBtnsLeft" #click="monthBack"><</button>
<button class="arrowBtnsRight" #click="monthForward">></button>
</div>
</template>
<script>
import Calendar from 'v-calendar/lib/components/calendar.umd'
export default {
name: 'calendar',
components:{
Calendar
},
data() {
return {
days : [],
counter: 0
};
},
computed:{
dates() {
return this.days.map(day => day.date);
},
attr() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth();
return [this.dates.map(date => ({
highlight:{class:'start'},
dates: date,
})),
{
highlight:'blue',
dates: {
start: new Date(year, month, 1), end:new Date(year, month, 1)
}
}
];
},
},
methods: {
onDayClick(day) {
const idx = this.days.findIndex(d => d.id === day.id);
if(this.counter > 1 || this.days.length > 2){
this.days = []
this.counter = 0
}
this.counter+=1
if (idx >= 0) {
this.days.splice(idx, 1);
} else {
this.days.push({
id: day.id,
date: day.date,
})
if(this.days.length == 2){
this.attr[1].dates.start = this.days[0].date
this.attr[1].dates.end = day.date
}
}
console.log(this.days,'count',this.counter,'attributes',this.attr[1].dates,'days.length',this.days.length)
}
}
</script>
I know. it is a component that was written without regard to vueJS best practices or standards, I had to write a bunch of hacks like this to, just do ordinary things like hide the calendar.

Is it possible to override a clock function so I could change its hours?

I'm designing a small browser project where you pick a city from the list and it presents you with the current time in city of your choice.
Although I've come across a problem.
The code only shows the correct time for a brief moment and then returns to the original UTC Standard time. The problem comes up at the "setTimeout" bit. Is there a possibility to override this? By adding clearTimeout perhaps?
function utcStandard(offset) {
var date = new Date();
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getUTCSeconds();
if (offset != undefined) {
hh += offset
};
hh = checkTime(hh);
mm = checkTime(mm);
ss = checkTime(ss);
document.getElementById("time").innerHTML =
hh + ":" + mm + ":" + ss;
var t = setTimeout(utcStandard, 500);
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
}
I decided to add the function to each item in the HTML list. For example.
<ul>
<li>Amsterdam</li>
</ul>
Like this - it is shorter and uses UTC where it is needed
I changed to minutes so you can have 5:30 for India for example
I did not consider DST for now
const pad = (num) => ("0"+num).slice(-2);
let t;
let curOffset = 0;
const reset = (offset) => {
clearInterval(t);
curOffset = offset ? offset : curOffset;
t = setInterval(utcStandard,500);
return false;
};
const utcStandard = () => {
var date = new Date(new Date().toUTCString().substr(0, 25))
date.setMinutes(date.getMinutes()+curOffset);
const hh = pad(date.getHours());
const mm = pad(date.getMinutes());
const ss = pad(date.getSeconds());
document.getElementById("time").innerHTML = "" + hh + ":" + mm + ":" + ss;
};
reset(0);
<span id="time"></span>
<ul>
<li>Amsterdam</li>
<li>London</li>
<li>Kolkata</li>
</ul>
The following implementation has two pieces of state:
dateString - the string representation of the time
offset - the currently chosen time offset
tick updates dateString repeatedly to capture the passage of time.
render renders the dateString to the DOM using requestAnimationFrame.
const freeze = Object.freeze
const DTF = new Intl.DateTimeFormat('en', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
let state = freeze({
dateString: '00:00:00',
offset: 0
})
function setOffset(o) {
clearTimeout(tickId)
state = freeze({ ...state, offset: o })
tick()
}
function toDateString(date = new Date) {
const d = DTF.formatToParts(date)
return `${d[0].value}:${d[2].value}:${d[4].value}`
}
let tickId = null
function tick() {
const date = new Date
date.setHours(date.getHours() + state.offset)
const dateString = toDateString(date)
tickId = setTimeout(tick, 16)
if(dateString !== state.dateString)
state = freeze({ ...state, dateString })
}
function render(state) {
document.getElementById('time').innerText = state.dateString
}
let previousState = null
function loop() {
if(state !== previousState) {
previousState = state
render(state)
}
requestAnimationFrame(loop)
}
tick()
requestAnimationFrame(loop)
input[type="radio"] {
display: none;
}
label {
font-family: sans-serif;
padding: 10px;
margin: 10px;
display: block;
cursor: pointer;
border-radius: 5px;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
input[type="radio"]+label {
background-color: rgba(0,220,220,0);
transition: background-color .5s ease-out 0s;
}
input[type="radio"]:checked+label {
background-color: rgba(0,220,220,1);
}
#time {
width: 100%;
font-family: sans-serif;
font-size: 2em;
text-align: center;
}
<input type="radio" name="group1" id="london" checked>
<label for="london" onclick="setOffset(0)">London</label>
<input type="radio" name="group1" id="amsterdam">
<label for="amsterdam" onclick="setOffset(1)">Amsterdam</label>
<input type="radio" name="group1" id="new-york">
<label for="new-york" onclick="setOffset(-4)">New York</label>
<div id="time"></div>

Javascript Booking Year Calendar

I'm looking for year calendar with select range functions, but i don't found this. And I decided customize Bootstrap Year Calendar - http://www.bootstrap-year-calendar.com/
And I'm stuck, my customised version is on http://ngrdanjski.com/calendar/
and I'm looking for help!
I added:
All days are disabled by default.
You can added Price periods, in this dates period you have enabled booking.
I want to add option when first click on the day it's first day of booking range, and second click is last day of booking range. Right now when click on day you have enable start date/first day, but when you click second time on day when you want to select end date, it's again start/first date. I wan't to have function to select start and end date. First click on day is start and second is end.
Code for current behavior is:
if(this.options.enableRangeSelection) {
cells.mousedown(function (e) {
if(e.which == 1)
{
var currentDate = _this._getDate($(this));
//console.log(currentDate);
if(_this.options.allowOverlap || _this.getEvents(currentDate).length == 0)
{
_this._mouseDown = true;
_this._rangeStart = _this._rangeEnd = currentDate;
_this._refreshRange();
}
}
});
cells.mouseenter(function (e) {
//console.log(e);
if (_this._mouseDown)
{
var currentDate = _this._getDate($(this));
if(!_this.options.allowOverlap)
{
var newDate = new Date(_this._rangeStart.getTime());
if(newDate < currentDate)
{
var nextDate = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() + 1);
while(newDate < currentDate)
{
if(_this.getEvents(nextDate).length > 0)
{
break;
}
newDate.setDate(newDate.getDate() + 1);
nextDate.setDate(nextDate.getDate() + 1);
}
}
else
{
var nextDate = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() - 1);
while(newDate > currentDate)
{
if(_this.getEvents(nextDate).length > 0)
{
break;
}
newDate.setDate(newDate.getDate() - 1);
nextDate.setDate(nextDate.getDate() - 1);
}
}
currentDate = newDate;
}
var oldValue = _this._rangeEnd;
_this._rangeEnd = currentDate;
if (oldValue.getTime() != _this._rangeEnd.getTime())
{
_this._refreshRange();
}
}
});
/* $(window).mouseup(function (e) {
if (_this._mouseDown)
{
_this._mouseDown = false;
_this._refreshRange();
var minDate = _this._rangeStart < _this._rangeEnd ? _this._rangeStart : _this._rangeEnd;
var maxDate = _this._rangeEnd > _this._rangeStart ? _this._rangeEnd : _this._rangeStart;
_this._triggerEvent('selectRange', {
startDate: minDate,
endDate: maxDate,
events: _this.getEventsOnRange(minDate, new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate() + 1))
});
}
}); */
}
URL: https://ngrdanjski.com/calendar/js/bootstrap-year-calendar.js
Full version: https://codepen.io/NGrdanjski/pen/bQGdRb
I don't have skill for this functionality, please help.
Tnx!
I edited your code a bit. I understand that you want to set two dates, the start and the end of the range, and all that happens in two clicks. I also added a check if the second date is after the first one, if it's not they will swap places, so the earlier date is the rangeStart. The dates are stored in rangeStart and rangeEnd:
Edit: here's a pen
cells.mousedown(function (e) {
if(e.which == 1)
{
var currentDate = _this._getDate($(this));
//console.log(currentDate);
if(_this.options.allowOverlap || _this.getEvents(currentDate).length == 0)
{
if(!_this._mouseDown) {
_this._mouseDown = true;
_this._rangeStart = _this._rangeEnd = currentDate;
_this._refreshRange();
}
else {
_this._mouseDown = false;
_this._rangeEnd = currentDate;
if(_this._rangeEnd.getTime() < _this._rangeStart.getTime()) {
var tempDate = _this._rangeEnd;
_this._rangeEnd = _this._rangeStart;
_this._rangeStart = tempDate;
}
// _this._refreshRange();
}
}
if(_this._rangeStart != _this._rangeEnd) {
console.log(_this._rangeStart.getDate() + ',' + _this._rangeEnd.getDate());
}
}
});

Disabling dates and specific weekdays in jquery datepicker

I'm trying to disable specific dates (i.e christmas etc) PLUS disabling certain weekdays per default in the jQuery UI datepicker, but I can't get it to work. I have the following:
<script type="text/javascript">
iDays = 2;
blockDays = [1,4,6];
$(document).ready(function () {
$.datepicker.setDefaults($.datepicker.regional['sv']);
$('.inpDate').datepicker({
dateFormat: 'yy-mm-dd',
minDate: iDays,
maxDate: 14,
showOtherMonths: true,
showStatus: true,
beforeShowDay: noHolidays
});
var disabledDays = ["12-24-2013", "12-25-2013", "12-26-2013", "12-31-2013", "1-1-2014"]
function noHolidays(date) {
return [!disableSpecificWeekDays(date) && !nationalDays(date)];
}
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1 || new Date() > date) {
return true;
}
}
return false;
}
function disableSpecificWeekDays(date) {
var daysToDisable = blockDays;
var day = date.getDay();
for (i = 0; i < daysToDisable.length; i++) {
if ($.inArray(day, daysToDisable) != -1) {
return [false];
}
}
return [true];
}
});
</script>
If I run ONLY the disableSpecificWeekDays in the "beforeShowDay" parameter it works fine, same goes with the nationalDays. But for some reason it FEELS like it's simply ignoring the date parameter if I call it through the noHoliday function.
In short, I need help!
Just noticed your question after having answered a similar/duplicate question. Instead of copying the code from there just have a look here: Hide weekdays and specific dates of jquery datepicker

Change the day background color in FullCalendar

I'm using FullCalendar in my asp.net application. I need to change the day background color.
What i have tried so far :
dayRender: function (date, cell) {
var today = new Date();
var end = new Date();
end.setDate(today.getDate()+7);
if (date.getDate() === today.getDate()) {
cell.css("background-color", "red");
}
var start = new Date();
start.setDate(today.getDate()+1);
while(start <= end){
//alert(start + "\n" + tomorrow);
if(start.getDate() == date.getDate()){
cell.css("background-color", "yellow");
}
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
}
This change background color of whole days. Demo
But my need is to change the background color of days, 7 days onward from current date.
Example
Today is 2013-July-29. I need to change the background color of below days.
2013-July-30
2013-July-31
2013-August-01
2013-August-02
2013-August-03
2013-August-04
2013-August-05
How can i do this ?
You can do it like this:
dayRender: function (date, cell) {
var today = new Date();
var end = new Date();
end.setDate(today.getDate()+7);
if (date.getDate() === today.getDate()) {
cell.css("background-color", "red");
}
if(date > today && date <= end) {
cell.css("background-color", "yellow");
}
}
http://jsfiddle.net/z8Jfx/7/
dayRender : function(date, cell) {
var idx = null;
var today = new Date().toDateString();
var ddate = date.toDate().toDateString();
if (ddate == today) {
idx = cell.index() + 1;
cell.css("background-color", "azure");
$(
".fc-time-grid .fc-bg table tbody tr td:nth-child("
+ idx + ")").css(
"background-color", "azure");
}
}

Categories