Change day in a function used by onclick, javascript - 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

Related

Time-based style changer how can I do it

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
}

Moment.js how to get week of month? (google calendar style)

I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?
EDIT:
I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.
It seems that moment.js does not have the method that implements the functionality that you are looking for.
However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7
For example:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
It looks like this is the number you are looking for, as demonstrated by the following test
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.
If you want to take this offset into account, you can use something something like the following if you are using moment.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Simple using moment.js
function week_of_month(date) {
prefixes = [1,2,3,4,5];
return prefixes[0 | moment(date).date() / 7]
}
This library adds the function moment.weekMonth()
https://github.com/c-trimm/moment-recur
I made some modifications based on feedback.
let weeks = moment().weeks() - moment().startOf('month').weeks() + 1;
weeks = (weeks + 52) % 52;
On days passing through the next year, the week value will be negative so I had to add 52.
What about something like:
weekOfCurrentMonth = (moment().week() - (moment().month()*4));
This takes the current week of the year, and subtracts it by the 4 times the number of previous months. Which should give you the week of the current month
I think the answer to this question will be helpful, even though it doesn't use moment.js as requested:
Get week of the month
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
There is a problem with #Daniel Earwicker answer.
I was using his function in my application and the while loop was infinite because of the following situation:
I was trying to figure out which week of december (2016) was the day 31.
the first day of december was day 336 of the year. The last day of december was day 366 of the year.
Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
I added the following lines to the code so the problem would be fixed:
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
year = m.year(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay && m.year() == year) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
It verifies if it is still in the same year of the date being veryfied
Here's Robin Malfait's solution implemented with the lightweight library date-fns
import {
differenceInDays,
startOfMonth,
startOfWeek,
getDate
} from 'date-fns'
const weekOfMonth = function (date) {
const firstDayOfMonth = startOfMonth(date)
const firstDayOfWeek = startOfWeek(firstDayOfMonth)
const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
return Math.ceil((getDate(date) + offset) / 7)
}
export default weekOfMonth
I'd do the following:
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(get(this, 'todaysDate')).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
That gets todaysDate and the endOfLastMonth and then uses Moment's built-in diff() method to compute the current month's week number.
It's not built-in, but basically you can subtract the week number of the start of the month from the week number of the date in question.
function weekOfMonth(m) {
return m.week() - moment(m).startOf('month').week() + 1;
}
Credit goes to code by original author, give him a star if it helped you.
How about this?
const moment = require("moment");
// Generate Week Number of The Month From Moment Date
function getWeekOfMonth(input = moment()) {
let dayOfInput = input.clone().day(); // Saunday is 0 and Saturday is 6
let diffToNextWeek = 7 - dayOfInput;
let nextWeekStartDate = input.date() + diffToNextWeek;
return Math.ceil((nextWeekStartDate) / 7);
}
Simple code, but has been working for me.
const weekOfTheMonth = (myMomentDate) => {
const startDay = moment(myMomentDate).startOf('week');
const day = parseInt(startDay.format('DD'),10);
if(day > 28){
return 5;
}
if((day > 21) && (day <= 28) ){
return 4;
}
if((day > 14) && (day <= 21) ){
return 3;
}
if((day > 7) && (day <= 14) ){
return 2;
}
return 1;
}

Using momentjs, how can I find which weekday number a specific day is in a month, and how many of a weekday are in a given month

Using momentjs, how can I find which weekday number a specific day is in a month, and how many of a weekday are in a given month?
Given any date, I need to extract if it is the First, Second, etc 'Saturday' of a specified month. Additionally, I need to know how many 'Saturdays' are in a given month. 'Saturday' is only an example. I will have a single date as my starting point of reference, and whatever date that is, I need the above stats on the Day of Week.
I started down the path of creating a second moment() and moving the week of the second object and comparing month names... but I want to do this using the momentjs native methods if possible.
The answer provided by dave is very good but needs a small modification:
Math.floor(DAYS_IN_MONTH / 7) + ((DAYS_IN_MONTH % 7 >= ((X - 1) % 7) + 1) ? 1 : 0)
Without this modification the formula incorrectly calculates the value for the weekday that falls on the 7th day of the month. For example, in a February with 28 days and the 7th day being a Monday, the original formula will calculate that there are 5 Mondays when in fact there are 4. The updated formula will correctly calculate that there are 4 Mondays.
Original:
Math.floor(28 / 7) + ((28 % 7 >= 7 % 7) ? 1 : 0) =
4 + ((0 >= 0) ? 1 : 0) =
4 + (true ? 1 : 0) =
4 + 1 =
5
Updated:
Math.floor(28 / 7) + ((28 % 7 >= ((7 - 1) % 7) + 1) ? 1 : 0) =
4 + ((0 >= (6 % 7) + 1) ? 1 : 0) =
4 + ((0 >= 6 + 1) ? 1 : 0) =
4 + ((0 >= 7) ? 1 : 0) =
4 + (false ? 1 : 0) =
4 + 0 =
4
As long as you know the date you are working with, and the number of days in that month, everything else is pretty simple.
If you know it's a Saturday, and you know it's the Xth day of the month, then you also know it is the Math.ceil(X/7)'th Saturday of the month.
Now, if you know there are DAYS_IN_MONTH days in the month, and you know a Saturday falls on the Xth day of the month, then you also know there are Math.floor(DAYS_IN_MONTH/7) + (DAYS_IN_MONTH%7 >= X%7 ? 1 : 0) days.

Date leap year validation

function checkDate(date)
{
//how to use this function since many people recommend this one
isLeap = new Date(date, 1, 29).getMonth() == 1;
return isLeap;
}
In html script, i wrote it as but i can't validate my Date of Order. I need to use javascript and it should be able to validate it including leap year. The function I used above can't work. Any helps will be appreciated.
To check if it's leap year :
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
to check if the extra day is valid -- is to check how many days were in that month (and if they equal to dd):
32 - new Date(2000, 1, 32).getDate() //1 here is FEB
do if some says : 29 feb 2000
so
32 - new Date(2000, 1, 32).getDate()//29
which is fine . cuz 29==29.
BUT
do if some says : 29 feb 2001
32 - new Date(2001, 1, 32).getDate()//28
and 28!=29 so it's not valid date.

Converting time string (e.g. 9:00 am) to 24 hour (0900)

var foo = '1:00 pm'
var bar = to24Hour(foo); //bar would be 1300
function to24Hour(time) {
time.match('(\d+):(\d+) ([ap]m)');
if ($1 > 12 && $3 = pm) {
$1 = 12 + $1;
}
return $1.$2;
}
I'm trying to convert 12 hour times to 24 hours "military" time (i.e. no colon). I'm having trouble with regex capture groups and javascript but above is what I think should work.
Can someone show me the correct way?
I think you misreferensed the regex groups... This should work.
function to24Hour(time) {
var hour, groups = (/(\d+):(\d+) ([ap]m)/i).exec(time);
hour = parseInt(groups[1], 10);
if (hour < 12 && groups[3] === "pm") {
hour += 12;
}
return hour.toString() + groups[2];
}

Categories

Resources