Time-based style changer how can I do it - javascript

Can someone explain me how to do a Time-based style changer in Javascript ? I've tried to do a test but it doesn't work. It only change the style when I manually modify in the code ">" to "<" in the if statement
This is the code I used
var myDate = new Date();
if(myDate.getHours() < 11.25) {
document.getElementById('box').style.backgroundColor = "red";
} else {
document.getElementById('box').style.backgroundColor = "black";
}

Try your condition as below. getHours will return integer value of hour while getMinutes will return integer value of minutes.
if (myDate.getHours() < 11 || (myDate.getHours() == 11 && myDate.getMinutes() < 15)) {
// your code
}

To further elabourate on my comment: getHours() returns an integer only, so it will always return 11 or 12 (and etc.), and never a fraction of an hour:
An integer number, between 0 and 23, representing the hour for the given date according to local time.
Therefore, comparing it against a non-integer value doesn't make a lot of sense in your case.
If you want to set up the if statement such that a certain style should be applied before a quarter past 11, then you need to compare it against getMinutes() too. This is assuming that by 11.25 you mean 11 hour + 0.25 hour, where 0.25h = 15mins:
if (myDate.getHours() === 11 && myDate.getMinutes() < 15 || myDate.getHours() < 11) {
// Logic here
}

Related

Javascript - sort and manipulate array of dates

I'm trying to prep a table which would have a header be an array of months/year. So the table would look roughly like such:
month1/year, month2/year, month3/year, etc....
field1:
field2:
field3:
The particular months/years are based upon a start and end date provided by a user. Based on some answers here, I have the logic working, however I hit a snag. By the way I've gone about getting the month (using getMonth()), it returns it as the index (so 0 for Jan, etc.). My first thought was just to +1, but clearly I then run into an issue with December -> January. My javascript skills are weak, so my only thought is to write in an if statement and adjust the final array after the fact.
Here's what I have so far:
function dateRange(startDate, endDate, steps = 1) {
const dateArray = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
dateArray.push(new Date(currentDate));
// Use UTC date to prevent problems with time zones and DST
currentDate.setUTCDate(currentDate.getUTCDate() + steps);
}
console.log("dateArray: ", dateArray)
const monthSet = dateArray.map(i => `${i.getMonth()}/${i.getFullYear()}`)
const header = [...new Set(monthSet)]
return header;
}
const dates = dateRange(isStart, isEnd);
console.log(dates);
It's not entirely clear what you're asking, sorry. But if you're wondering how to increment the month index without getting numbers like 13, 14, etc., you can use the modulo operator:
1 % 12 === 1;
2 % 12 === 2;
3 % 12 === 3;
10 % 12 === 10;
12 % 12 === 0;
13 % 12 === 1;
You should be safe simply adding 1 to .getMonth(), since that function will only ever yield values 0 though 11.

Does check day and hour need to check timezone?

My code to check day and hour like this :
function checkDay() {
var day = new Date();
if (day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 9 && day.getHours() < 17) {
return true;
} else {
return false;
}
}
I want every Monday to Friday 9 to 17, it's true. Apart from that, it is false
I had test it and it works. Is it necessary to check Timezone?
My position at Indonesia (GMT + 7)
If I implement timezone, it like this :
function checkDay() {
const offsetHours = new Date().getTimezoneOffset() / 60;
const day = new Date();
day.setHours(day.getHours() + offsetHours);
return day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 2 && day.getHours() < 10;
}
Is it necessary to check Timezone like that?
Your first piece of code is already correct because getHours and getDay already operate in the local time zone. As per the MDN Date documentation:
Note: It's important to keep in mind that while the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.
Likewise the ECMAScript specifications (e.g. ECMA 262, 2015 edition) describe the behaviour as going via the LocalTime abstract operation:
The abstract operation LocalTime with argument t converts t from UTC to local time

Best way to normalize time in JS

I have some data that's inconsistent. It's all time related but I have some records that shows 3pm others 14:00.
Is there an easy way to normalize that in JS?
Thanks
This function will return you a 24-hour-formatted time
function normaliseTime(time) {
// If there is AM/PM in the string, do conversion
if (time.toUpperCase().indexOf('M') >= 0) {
// Remove the AM/PM text and split the hour and minute
var tmArray = time.replace(/\D/g, '').split(':');
// If PM, add 12 to the hour
if (time.toUpperCase().indexOf('PM') >= 0) {
tmArray[0] = parseInt(tmArray[0]) + 12;
}
// If minutes were not provided (i.e., 3PM), add 00 as minutes
if (tmArray.length < 2) {
tmArray[1] = '00';
}
return tmArray.join(':');
}
// If there was no AM/PM in the input, return it as is
return time;
}

Change day in a function used by onclick, javascript

Hey there i have the following problem. I am sure you could help me:
I have a button that change the hour +1 hour or - 1 hour. But the date jumps from 00UTC to 23 UTC on the same day and not the day before.
Note: addZero completes the string from 1 to "01" (it is because an image string needs 01 02 03 )
function switch_image(i) {
if (i == 0) {
d.setUTCHours(d.getUTCHours() - 1);
if (d.getUTCHours() == 23) {
d.setUTCDate(d.getUTCDate() - 1);
}
h = addZero(d.getUTCHours());
} else {
d.setUTCHours(d.getUTCHours() + 1);
if (d.getUTCHours() == 0) {
d.setUTCDate(d.getUTCDate() + 1);
}
h = addZero(d.getUTCHours());
}
}
Thanks a lot for your help ;)
I found the solution by myself. I forgot to set the variable for days (it s t, for hpurs its h) new. Best regards .
See the following function which adds a constant value to another date using Date.UTC(1970,0,1) as a starting value (Jan 1, 1970 is the Unix epoch). Note that months and years aren't included because they aren't constant times (there are leap years and months don't span the same number of days).
Date.prototype.addTime = function(days,hours,minutes,seconds,milliseconds){
for(var i=0;i<arguments.length;i++){
arguments[i]=parseInt(arguments[i]);
}
return new Date(this.getTime() +
Date.UTC(1970, 0,
(isNaN(days) ? 0 : days) + 1,
isNaN(hours) ? 0 : hours,
isNaN(minutes) ? 0 : minutes,
isNaN(seconds) ? 0 : seconds,
isNaN(milliseconds) ? 0 : milliseconds));
}
document.body.innerHTML = new Date(Date.now()).addTime(1,1).toString(); //Adds 1 day,1 hour
Reference: MDN

How can I determine whether a given string represents a date?

Is there an isDate function in jQuery?
It should return true if the input is a date, and false otherwise.
If you don't want to deal with external libraries, a simple javascript-only solution is:
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
UPDATE: !!Major Caveat!!
#BarryPicker raises a good point in the comments. JavaScript silently converts February 29 to March 1 for all non-leap years. This behavior appears to be limited strictly to days through 31 (e.g., March 32 is not converted to April 1, but June 31 is converted to July 1). Depending on your situation, this may be a limitation you can accept, but you should be aware of it:
>>> new Date('2/29/2014')
Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time)
>>> new Date('3/32/2014')
Invalid Date
>>> new Date('2/29/2015')
Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
>>> isDate('2/29/2014')
true // <-- no it's not true! 2/29/2014 is not a valid date!
>>> isDate('6/31/2015')
true // <-- not true again! Apparently, the crux of the problem is that it
// allows the day count to reach "31" regardless of the month..
simplest way in javascript is:
function isDate(dateVal) {
var d = new Date(dateVal);
return d.toString() === 'Invalid Date'? false: true;
}
Depending on how you're trying to implement this, you may be able to use the "validate" jQuery plugin with the date option set.
There's no built-in date functionality in jQuery core...and it doesn't really do anything directly to help with dates, so there aren't many libraries on top of it (unless they're date pickers, etc). There are several JavaScript date libraries available though, to make working with them just a bit easier.
I can't answer for sure what's best...it depends how they're entering it and what culture you're dealing with, keep in mind that different cultures are used to seeing their dates in different format, as a quick example, MM/DD/YYYY vs YYYY/MM/DD (or dozens of others).
The best way to get user date input is a date picker that only provides valid dates.
It can be done with a string, but you are liable to rile your users by demanding they use your chosen format.
You need to specify in your validator if dates precede months.
This uses a second argument to enforce the order.
With no second argument it uses the computer's default order.
// computer default date format order:
Date.ddmm= (function(){
return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()
allow month names as well as digits: '21 Jan, 2000' or 'October 21,1975'
function validay(str, order){
if(order== undefined) order= Date.ddmm? 0: 1;
var day, month, D= Date.parse(str);
if(D){
str= str.split(/\W+/);
// check for a month name first:
if(/\D/.test(str[0])) day= str[1];
else if (/\D/.test(str[1])) day= str[0];
else{
day= str[order];
month= order? 0: 1;
month= parseInt(str[month], 10) || 13;
}
try{
D= new Date(D);
if(D.getDate()== parseInt(day, 10)){
if(!month || D.getMonth()== month-1) return D;
}
}
catch(er){}
}
return false;
}
The problem is that entering in February 31st will return a valid date in JavaScript. Enter in the year, month, and day, turn it into a date, and see if that date matches what you input, instead of some day in March.
function isDate(y, m, d) {
var a = new Date(y, m-1, d);
// subtract 1 from the month since .getMonth() is zero-indexed.
if (a.getFullYear() == y && a.getMonth() == m-1 && a.getDate() == d) {
return true;
} else {
return false;
}
}
Technically, this is vanilla JavaScript, since jQuery doesn't really expand on the native Date object.
Date.parse will prb sort you out, without the need for jquery:
http://www.w3schools.com/jsref/jsref_parse.asp
Above removed after some kind soul pointed out how basic parseDate really is.
There is also a $.datepicker.parseDate( format, value, options ) utility function in the JQuery UI Datepicker plugin:
https://api.jqueryui.com/datepicker/
I arrived at this solution, made more complicated as I use the European format and javascript is clearly american!
function CheckDate()
{
var D = document.getElementById('FlightDate').value;
var values = D.split("-")
var newD = values [1] + "/" + values [0] + "/" + values[2]
var d = new Date(newD);
if(d == 'Invalid Date')document.getElementById('FlightDate').value = "";
}
Messy, but does the job.
If your users are american and put the day in the middle, (which I'll never understand!), then you can leave out the split and creation of the newD.
It is probable that I can override the default americanism in the JS by setting culture or some such, but my target audience is exclusively European so it was easier to rig it this way.
(Oh, this worked in Chrome, haven't tested it on anything else.)
If you don't want to use the jquery plugin I found the function at:
http://www.codetoad.com/forum/17_10053.asp
Works for me. The others I found don't work so well.
UPDATED:
From the cached version of the page at: http://web.archive.org/web/20120228171226/http://www.codetoad.com/forum/17_10053.asp
// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.
// The function returns true if a valid date, false if not.
// ******************************************************************
function isDate(dateStr) {
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
return false;
}
month = matchArray[1]; // p#rse date into variables
day = matchArray[3];
year = matchArray[5];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
alert("Month " + month + " doesn`t have 31 days!")
return false;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day == 29 && !isleap)) {
alert("February " + year + " doesn`t have " + day + " days!");
return false;
}
}
return true; // date is valid
}
I guess you want something like this. +1 if it works for you.
HTML
Date : <input type="text" id="txtDate" /> (mm/dd/yyyy)
<br/><br/><br/>
<input type="button" value="ValidateDate" id="btnSubmit"/>
jQuery
$(function() {
$('#btnSubmit').bind('click', function(){
var txtVal = $('#txtDate').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
});
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
dtYear = dtArray[5];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
});
CSS
body{
font-family:Tahoma;
font-size : 8pt;
padding-left:10px;
}
input[type="text"]
{
font-family:Tahoma;
font-size : 8pt;
width:150px;
}
DEMO
You should use moment.js it's the best lib to handle all kind of dates.
Solution to your problem:
var inputVal = '2012-05-25';
moment(inputVal , 'YYYY-MM-DD', true).isValid();

Categories

Resources