I'm having a little bit of trouble trying to make it 'snow' only on Christmas day. I figured out how to grab the day but I'm not sure how make it call SnowStorm() correctly.
var christmas = {
month: 11,
date: 25
}
function isItChristmas() {
var now = new Date();
var isChristmas = (now.getMonth() == christmas.month && now.getDate() == christmas.date);
if (isChristmas)
return ;
else
return ;
}
var snowStorm = null;
function SnowStorm() {
(snowstorm code)
}
snowStorm = new SnowStorm();
Here's the version if you are planning to make a function (not a class):
var christmas = {
month: 12,
date: 25
}
function isItChristmas() {
var now = new Date();
return (now.getMonth() == christmas.month && now.getDate() == christmas.date);
}
if (isItChristmas()){
SnowStorm();
}else{
//not a christmas
}
function SnowStorm() {
(snowstorm code)
}
Here's the one if you are planning to make a class:
var christmas = {
month: 12,
date: 25
}
function isItChristmas() {
var now = new Date();
return (now.getMonth() == christmas.month && now.getDate() == christmas.date);
}
var storm = new SnowStorm();
if (isItChristmas()){
storm.Snow();
}else{
//not a christmas
}
function SnowStorm() {
this.Snow = function(){
(snowstorm code)
}
}
First, you are not returning anything on the isItChristmas function.
Second, in the SnowStorm function just add
if (isItChristmas) {
(your code here)
}
You need to return a boolean value from the isItChristmas function:
function isItChristmas() {
var now = new Date();
return (now.getMonth() + 1 == christmas.month &&
now.getDate() == christmas.date);
}
and then call it:
function SnowStorm() {
if (isItChristmas()) {
// your snowstorm code here
// that will execute only on Christmas
}
}
By the way you will notice that the .getMonth() method returns the month from 0 to 11, so you need to add 1 as shown in my example, otherwise your code will run on 25th of November.
Related
I'm not sure I can fully explain myself but I have a project and this project serves a JSON that includes missions. This JSON file can be updated continuously. structure could be like below:
[
{
"module_id": 5,
"title": "TITLE 1",
"media_path": "/img/src/aa.jpg",
"start_time": "2019-08-13 21:50:00",
"finish_time": "2019-08-30 23:59:00"
},
{
"module_id": 10,
"title": "TITLE 2",
"media_path": "/video/src/aa.mp4",
"start_time": "2019-08-30 23:59:00",
"finish_time": "2019-09-30 23:59:00"
},
{
"module_id": 15,
"title": "TITLE 3",
"media_path": "/img/src/cc.jpg",
"start_time": "2019-09-30 23:59:00",
"finish_time": "2019-10-30 23:59:00"
}
]
My question is:
Can I update page without refreshing according to the datetime in JSON file. When the next start_time approaches, I wanna load the media in the background and when the start_time comes I wanna change the design of page according to module_id. Every module_id will have own page design.
So the page design and content will change without refreshing page according to module_id's own design when time comes.
Hope I could explain myself. Thanks for your answers.
// Assuming the JSON file is called "missions.json"
class MissionsChecker ()
{
constructor () {
this.loadMissionsFile("missions.json");
this.running = false;
}
start () {
if (!this.running) {
this.checkMissions();
this.running = true;
}
}
stop () {
if (this.running) {
clearInterval(this.missionChecker);
this.running = false;
}
}
loadMissionsFile (filename) {
var req = new XMLHttpRequest();
req.open("GET", filename, false);
var self = this;
req.onreadystatechange = function () {
if (this.status == 200 && this.readyState == 4) {
self.missions = JSON.parse(this.responseText);
}
}
req.send(null);
}
getFullDate () {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
if (month.length < 2) {
month = "0" + String(month);
}
return String(year) + "-" + String(month) + "-" + String(day);
}
getFullTime () {
var date = new Date();
var hour = date.getFullYear();
var minutes = date.getMonth();
var seconds = date.getDate();
if (hour.length < 2) {
hour = "0" + String(hour);
}
if (minutes.length < 2) {
minutes = "0" + String(minutes);
}
if (seconds.length < 2) {
seconds = "0" + String(seconds)
}
return String(hour) + ":" + String(minutes) + ":" + String(seconds);
}
select (selector) {
return document.querySelector(selector);
}
checkMissions () {
var self = this;
this.missionChecker = setInterval(function () {
for (var missionGroup of self.missions) {
var currentDateTime = self.getFullDate() + " " + self.getFullTime();
if (missionGroup.start_time == currentDateTime) { // You'd probably need to modify this
document.title = missionGroup.title;
var imgElem = this.select(".img-holder"); // where ".img-holder" is the element that is to have its background image changed
imgElem.style.imageBackground = missionGroup.media_path;
if (missionGroup.module_id == match) { // where "match" is the module_id to be matched
// your UI-changing JavaScript code will go in here
}
}
}
}, 1000);
}
}
Please feel free to correct me if I'm wrong. Oh and to check for missions run new MissionsChecker().start()
You could use setTimeout then each interval checks the current time new Date() against all JSON file times. Something a little like this;
jsonFiles.forEach(file => {
const fileStart = new Date(file.start_time);
const fileEnd = new Date(file.end_time);
const now = new Date();
if(fileStart <= now && fileEnd >= now){
// chnage ui here
}
I'm trying to disable specific dates and enable only specific days of the week on a jQuery UI datepicker.
This is inside a Wordpress/Woocommerce theme and I'm trying to solve some bugs but I'm here for hours trying to figure out for a solution and even tried every solution I found on StackOverflow and other websites, but nothing seems to work.
My objective is to enable only chosen days of the week to be available, but when a date is chosen and bought, I need to disable it too. I successfully disabled the days of the week that I need to be disabled, but I can't do even a hardcoded prototype about the bought dates that should be disabled.
The code (with some hardcoded sample):
$(document).ready(function(){
var available_days = ["3"]; //it comes from the database
var today = new Date();
var tour_start_date = new Date( 1525132800000 ); //it comes from the database
var tour_end_date = new Date( 1546214400000 ); //it comes from the database
var available_first_date = tour_end_date;
var lang = 'en_UK';
lang = lang.replace( '_', '-' );
today.setHours(0, 0, 0, 0);
tour_start_date.setHours(0, 0, 0, 0);
tour_end_date.setHours(0, 0, 0, 0);
if ( today > tour_start_date ) {
tour_start_date = today;
}
function DisableDays(date) {
var day = date.getDay();
if ( available_days.length == 0 ) {
if ( available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
return true;
}
if ( $.inArray( day.toString(), available_days ) >= 0 ) {
if ( available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
return true;
} else {
return false;
}
}
if ( $('input.date-pick').length ) {
if ( lang.substring( 0, 2 ) != 'fa' ) {
$('input.date-pick').datepicker({
startDate: tour_start_date,
endDate: tour_end_date,
beforeShowDay: DisableDays,
language: lang
});
$('input[name="date"]').datepicker( 'setDate', available_first_date );
} else {
var date_format = $('input.date-pick').data('date-format');
$('input.date-pick').persianDatepicker({
observer: true,
format: date_format.toUpperCase(),
});
}
}
});
Please review: http://api.jqueryui.com/datepicker/#option-beforeShowDay
A function that takes a date as a parameter and must return an array with:
[0]: true/false indicating whether or not this date is selectable
[1]: a CSS class name to add to the date's cell or "" for the default presentation
[2]: an optional popup tooltip for this date
The issue in your code was that you were only returning true or false when an Array was needed. For example:
$(function() {
var available_days = ["3", "5"]; //it comes from the database
var today = new Date();
var tour_start_date = new Date(1525132800000); //it comes from the database
var tour_end_date = new Date(1546214400000); //it comes from the database
var available_first_date = tour_end_date;
var lang = 'en_UK';
lang = lang.replace('_', '-');
today.setHours(0, 0, 0, 0);
tour_start_date.setHours(0, 0, 0, 0);
tour_end_date.setHours(0, 0, 0, 0);
if (today > tour_start_date) {
tour_start_date = today;
}
function DisableDays(date) {
var day = date.getDay();
var found = false;
if (available_days.length == 0) {
if (available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
found = true;
}
if ($.inArray(day.toString(), available_days) >= 0) {
console.log(day + " in Array");
if (available_first_date >= date && date >= tour_start_date) {
available_first_date = date;
}
found = true;
}
console.log(day, found);
return [found, "tour-date", "Tour Date"];
}
if ($('input.date-pick').length) {
if (lang.substring(0, 2) != 'fa') {
$('input.date-pick').datepicker({
startDate: tour_start_date,
endDate: tour_end_date,
beforeShowDay: DisableDays,
language: lang
});
$('input[name="date"]').datepicker('setDate', available_first_date);
} else {
var date_format = $('input.date-pick').data('date-format');
$('input.date-pick').persianDatepicker({
observer: true,
format: date_format.toUpperCase(),
});
}
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Date: <input type="text" class="date-pick" name="date" />
I ran into a deadly chaos on datepicker issues.
Who can solve my problem I can give 100 point as a return.
When I click the calendar on 2016-08-23 it will show me the 2016-08-22 as the date value.
Furthermore, the date value in angular model is also not correct.
I want to make the output can be consistent.
To reproduce the buggy issue, change your timezone between LA and TOKYO
DEMO site: https://test.jiyubi.com/tour_package/home
controller js
app.controller('tourPackageStartDatePickerCtrl',
function ($scope) {
$scope.initStartDate = function () {
$scope.startDate = $scope.startDate || null;
};
$scope.initStartDate();
$scope.dateOptions = {
baseDate: $scope.startDate,
minDate: $scope.startDate || moment.utc().toDate(),
};
$scope.openStartDateClick = function () {
$scope.startDatePopup.opened = true;
};
});
app.controller('tourPackageEndDatePickerCtrl',
function ($scope, $rootScope) {
$scope.clear = function () {
$scope.endDate = null;
};
$scope.endDateOptions = {
dateDisabled: disabledDays,
baseDate: new Date(),
};
$scope.openEndDateClick = function () {
$scope.endDatePopup.opened = true;
};
$scope.$watch("endDate", function (new_val, old_val) {
if (new_val && moment(new_val).isValid()) {
setTravelDateRange($scope.startDate, $scope.endDate);
}
}, true)
function setTravelDateRange(startDate, endDate) {
var start_date = moment_with_TAIPEI_TZ(startDate).format("YYYY/MM/DD");
var end_date = moment_with_TAIPEI_TZ(endDate).format("YYYY/MM/DD");
moment(startDate.toDateString()).tz("Asia/Taipei").format("YYYY/MM/DD");
$scope.q_param.startDate = start_date;
$scope.q_param.date_range = start_date + "-" + end_date;
}
});
helper.js
function moment_with_TAIPEI_TZ(time){
return moment(time).tz("Asia/Taipei");
}
function MOMENT_WITH_LOCAL(time){
return moment(time).local();
}
function discard_timezone(value) {
return moment.utc(value).format(DEFAULT_MOMENT_TIME_FORMAT);
}
function getYYYYMMDD(value) {
return moment.utc(value).format("YYYY/MM/DD");
}
function date_without_timezone(value) {
return moment.utc(value).toDate();
}
It's may be because of a timezone issue.
Could you please try to convert to date without considering the timezone?
this.convertToDateWithoutTimezone = function(date) {
if (date.toString().match(/(\d\d\d\d)-(\d\d)-(\d\d)/)) {
var year = $filter('date')(date.slice(0, 10), 'yyyy'),
month = $filter('date')(date.slice(0, 10), 'MM'),
day = $filter('date')(date.slice(0, 10), 'dd');
return new Date(year, month - 1, day);
} else {
return new Date(date);
}
};
A friend of mine has a Drupal 6 site where users are able to select a future date for a delivery. Recently, several customers have been selecting weekends and holidays for delivery dates, and my friend would like to prevent them from doing so.
This is the code we're currently using to block out weekends. Can someone help modify it to also block out Christmas and New Years Eve?
Thanks very much!
drupal_add_js("
Drupal.behaviors.date_popup = function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], function(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// CUSTOM
datePopup.settings.beforeShowDay = function(date) {
var day = date.getDay();
return [(day != 0 && day != 6), ''];
}
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
}
}
});
}
};
",'inline');
UPDATE:
I ended up doing the following, which works for our needs:
drupal_add_js("
Drupal.behaviors.date_popup = function (context) {
for (var id in Drupal.settings.datePopup) {
$('#'+ id).bind('focus', Drupal.settings.datePopup[id], function(e) {
if (!$(this).hasClass('date-popup-init')) {
var datePopup = e.data;
// CUSTOM
datePopup.settings.beforeShowDay = function(date) {
var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;
var closedDates = [[12, 31, 2015], [12, 25, 2015]];
var closedDays = [[Saturday], [Sunday]];
for (var i = 0; i < closedDays.length; i++) {
if (day == closedDays[i][0]) {
return [false];
}
}
for (i = 0; i < closedDates.length; i++) {
if (date.getMonth() == closedDates[i][0] - 1 &&
date.getDate() == closedDates[i][1] &&
date.getFullYear() == closedDates[i][2]) {
return [false];
}
}
return [true];
}
// Explicitely filter the methods we accept.
switch (datePopup.func) {
case 'datepicker':
$(this)
.datepicker(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
case 'timeEntry':
$(this)
.timeEntry(datePopup.settings)
.addClass('date-popup-init')
$(this).click(function(){
$(this).focus();
});
break;
}
}
});
}
};
",'inline');
I can go back from date to year in datepicker. But when I try to come back to date, when i clicked on year, datepicker automatically hide.
var datePickerOptions = this.data || {};
datePickerOptions.format = datePickerOptions.format || "mm-dd-yyyy";
datePickerOptions.language = datePickerOptions.language || this.lang.code;
var $context = this;
var dateContainer = this.container.find(".datepicker");
dateContainer.datepicker(datePickerOptions).on('changeDate', function (ev) {
// here i'm getting the value
});
This because of bootstrap-datepicker.js .
on click event you can find like following.
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1);
this.fill();
}
instead of this.fill(), if you use like following code, this will work as you expected.
if (target.is('.month')) {
if (!this._o.changeMonth) {
this.fill();
}
}
else {
if (!this._o.changeYear) {
this.fill();
}
}
I hope, this will help you. :-)