Problem in adding days / month / year to a given date using javascript? - javascript

I trying to add days / months / year to a given date and map it to an input field
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setYear(2011);
document.getElementById("test").innerHTML=d;
d.setDate(d.getDate()+20);
document.getElementById("test").innerHTML+=""+d.getDate()+"/"+d.getMonth()+"/"+d.getYear("YY");
this actually prints out
Fri Jul 15 2011 12:45:48 GMT+0530 (India Standard Time)
4/7/111
actually this is wrong.. it should print out 5/7/2011.. i think by default the system takes as "30" days for a month and adds the +20 days.. but actually Jun has 30 days so that result should be 5/7/2011..
any suggestion about what goes wrong in here.. any alternative for this?

At the first, you have better to use getFullYear to get year as 2011. You did get number from getDate() and add 20. This break Date. You should get long value from getTime(), and add milli-seconds.
<div id="test"></div>
<script>
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setFullYear(2011);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
d.setTime(d.getTime()+1000*60*60*24*20);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
</script>

> var d = new Date();
> d.setDate(15);
> d.setMonth(06);
> d.setYear(2011);
is equivalent to:
var d = new Date(2011,6,15); // 15 Jul 2011
Months are zero based (January = 0, December = 11).
Date.prototype.getYear is specified in ECMA-262 ed5 as Return YearFromTime(LocalTime(t)) − 1900. so:
alert(d.getYear()); // 111
whereas:
alert(d.getFullYear()); // 2011

i think by default the system takes as "30" days for a month and adds the +20 days.. but actually May has 31 days so that result should be 5/7/2011.
You are interpreting it a wrong way, Month in a date starts with 0 - Jan..
So as per the date entered by you it comes Jul 15 2011 on the month number 6.
When you add 20 to date it will be Aug 04 2011 and you are directly getting month number which is 7 - i.e. Aug which misleads your calculation. And for the year, yes it is you should getFullYear
Read this to get your basics correct..

Related

Problem while modifying a date (modification is wrong)

I'm trying to make a calendar in Angular. For this I have implement a drag & drop functionnality to be able to move one appointment from a day to another one.
But I have something strange, when I try to move an appointment it seems working, but when I try to move it from the 1st april to the 31 march then the date is modified to the 1st march.
When I drop my appointment I emit a change with my appointment data and the new day:
drop(evt) {
let schedule: Schedule;
schedule = evt.data.schedule;
// Emit change
this.scheduleChange.emit({schedule, day: this.day});
}
Then I edit my appointment:
scheduleChanged(evt) {
const schedule = this.createScheduleFromObject(evt.schedule);
const day = evt.day;
console.log(day);
if (this.isSameDate(schedule.start, schedule.end)) {
schedule.start.setDate(day.getDate());
schedule.start.setMonth(day.getMonth())
schedule.start.setFullYear(day.getFullYear());
schedule.end.setDate(day.getDate());
schedule.end.setMonth(day.getMonth());
schedule.end.setFullYear(day.getFullYear());
console.log(schedule);
}
}
I think the problem is when I transform my object to a Schedule class:
createScheduleFromObject(obj: any) {
const schedule: Schedule = Object.assign(new Schedule(null, '', '', '', new Date(), new Date()), obj);
console.log(obj.start);
schedule.start = new Date(obj.start);
schedule.end = new Date(obj.end);
console.log(schedule.start);
return schedule;
}
This function return the good date here is the output of the console log:
2020-04-01T21:31:49.640Z
Wed Apr 01 2020 23:31:49 GMT+0200
But when I modify it in the scheduleChanged function even if the day is the 31st march as I have in the console log:
Tue Mar 31 2020 00:00:00 GMT+0200
The start date of my schedule is set to :
Sun Mar 01 2020 23:33:19 GMT+0100
Why ?
I suspect this is a duplicate of Javascript setMonth shows improper date. What is likely happening in your case is that moving a date for April to 31 March, you are setting the day in April to a non–existent date, so it rolls over to the next month.
When setting the values of a date one at a time, you may have issues where the date of the starting Date doesn't exist in the month being set. So when setting the values of a date to new values, do it all in one go, so instead of:
schedule.start.setDate(day.getDate());
schedule.start.setMonth(day.getMonth())
schedule.start.setFullYear(day.getFullYear());
do:
schedule.start.setFullYear(day.getFullYear(), day.getMonth(), day.getDate());
So in your case, moving a date from 1 April to 31 March:
The April date is set to 31, which doesn't exist so rolls over to 1 May
The month is set to March
Year is set to whatever
So you end up with a Date for 1 March. Setting the values in one go fixes that so:
(2020-04-01).setFullYear(2020, 2, 31) -> 2020-03-31
When setting the year, you can also set the month and day, when setting month you can set the month and day. Similarly for time, setting hours can set hours, minutes, seconds and milliseconds. Setting minutes can set minutes, seconds and milliseconds, etc.

get week number from date in whole week base in javascript

I have searched the web and found the script to get the week number in year. However my counting is difference. The below image is the week number I want to get. When I tested using '1/5/2015', my code got week number is 2, but the week number should be 1 in my requirement. Would someone can help me. Thanks in advance.
I found the javascript at IamSilviu/Get week number
There is my code:
function myWeekNumber(thisDate) {
var dt = new Date(thisDate)
var onejan=new Date(dt.getFullYear(), 0, 2);
return Math.ceil((((dt - onejan) / 86400000) + onejan.getDay() + 1) / 7); }
The algorithm you're trying to implement seems to be that:
Weeks start on Sunday
The first week of the year is the one that has any days in the year, e.g. 1 Jan 2016 was a Friday, so the first week of 2016 started on Sunday 27 December 2015
In this case, it's best to use UTC methods to avoid daylight saving issues:
function getWeekNumberNonISO(d) {
// Create UTC equivalent for 23:59:59.999 on the passed in date
var sat = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(),23,59,59,999));
// Set to Saturday at end of week
sat.setUTCDate(sat.getUTCDate() + 6 - sat.getUTCDay());
// Get first day of year
var firstDay = new Date(Date.UTC(sat.getUTCFullYear(), 0, 1));
// Set to Sunday on or before, i.e. first day of first week in year
firstDay = firstDay.setUTCDate(firstDay.getUTCDate() - firstDay.getUTCDay());
// Week number is difference in dates divided by ms/week rounded
return Math.round((sat - firstDay)/(6.048e8));
}
// Get week number for Mon 5 Jan 2015
console.log(getWeekNumberNonISO(new Date(2015,0,5))); // 2
// Get week number for Sat 31 Dec 2011
console.log(getWeekNumberNonISO(new Date(2011,11,31))); //53
// Get week number for Sat 1 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,1))); // 1
// Get week number for Sun 2 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,2))); // 2
Js has function inbulid function which can be used to fetch the date from the given date of the week getweek().
var week=date.getWeek()

How to deduct time in 24 hours using moment

My use case is very simple, How do i deduct the current time in 24 hours. Technically it is like snapchat, 24 hours from now it will dissapear, hence why I need to deduct the time.
11:50 PM - 10 Jan 2017
I want to deduct the current time to the next 24 hours time only
(10:50 PM - 11 Jan 2017) - (11:50 PM 10 Jan 2017) = 1 hour left
How would I do such thing in Moment.js ?
You can add -24 hours. See moment.add
moment(date).add(-24, 'hours');
And to display relative time you can use moment.fromNow
I think this would help you :
//valid formats to subtract
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
//easy examples
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
Read http://momentjs.com/docs/#/parsing/ for documentation on moment js parse.
This just might work. It did work in JSFiddle http://jsfiddle.net/Bjolja/p2bcm2oa/
var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");
Yes you should use moment.js take a look here
Moment from method
In fact you can deduct time passed between to dates like this
var start = moment("10:50 PM - 11 Jan 2017");
var end = moment("11:50 PM 10 Jan 2017");
start.from(end); // "1 hour"

getMonth getUTCMonth difference result

I found and inconsistent result when using the JavaScript date.getMonth() and date.getUTCMonth(), but only with some dates. The following example demonstrates the problem:
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<p id="demo">Click the button to display the month</p>
<script type="text/javascript">
function myFunction()
{
var d = new Date(2012, 8, 1);
var x = document.getElementById("demo");
x.innerHTML=d;
x.innerHTML+='<br/>result: ' + d.getMonth();
x.innerHTML+='<br/>result UTC: ' + d.getUTCMonth();
}
</script>
</body>
</html>
The output of this example is:
Sat Sep 01 2012 00:00:00 GMT+0100 (Hora de Verão de GMT)
result: 8
result UTC: 7
If i change the date to (2012, 2, 1) the output is:
Thu Mar 01 2012 00:00:00 GMT+0000 (Hora padrão de GMT)
result: 2
result UTC: 2
In the first example, getMonth returns 7 and getUTCMonth returns 8. In the second example, both returns the same value 2.
Does anyone already experiences this situation? I am from Portugal and i think that it has something to be with my GMT but i don't understand why this is happening, because the examples are running in same circumstances.
Thanks in advances
You will see that, depending on YOUR TIMEZONE, the console logs may be different. I chose the first of the month '01' because it will be given a midnight default time '00:00:00', which will result in some timezones yielding February instead of March (you can get the full scoop here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) :
let date1 = '2019-03-01'; // defaults to UTC
let date2 = '2019-03-01T14:48:00'; // LOCAL date/time
let dt1 = new Date(date1);
let dt2 = new Date(date2)
let month1 = dt1.getMonth();
let month2 = dt2.getMonth();
console.log("mon1: " + month1);
console.log("mon2: " + month2);
You will find that it is caused by DST difference.
Universal Time Zone date methods are used for working with UTC dates
Date returns month between 0 to 11
new Date(1976, 01 , 18) -
Wed Feb 18 1976 00:00:00 GMT+0530 (India Standard Time)
*getUTCDate return same as getDate() but returns Date based on World Time Zone, same with month and year
new Date(1976, 01 , 18).getUTCDate() -
17
new Date(1976, 01 , 18).getDate() -
18
new Date(1976, 02 , 18).getUTCMonth() -
2
new Date(1976, 01 , 18).getMonth() -
1
new Date(1976, 01 , 18).getYear() -
76
new Date(1976, 01 , 18).getUTCFullYear() -
1976
new Date(1976, 01 , 18).getFullYear() -
1976
A Date in js is just a timestamp, meaning there is no timezone information in any Date instance. A date is an absolute timed event (in opposition to a wall clock time which is relative to your timezone).
So… when you print the date to the console, because there is no timezone information in the date object, it will use your browser's timezone to format the date.
This is embarrassing because if you provide the same date to 2 clients, one in US and the other one in EU and ask them the date's month, because both are using their own timezone, you might end up with different answers.
To prevent this, getUTCMonth(); will use a default timezone of UTC (+0) instead of the client's browser so that the answer will be consistent whatever the client's timezone.

JavaScript Dateobject Increment goes wrong

I want to increment the year-value of a given date, but this goes wrong.
this is my code:
var endDate = entry.start;
endDate.setDate(endDate.getFullYear() + 5);
and for comparison the output (console.log) is:
Date {Thu Jun 30 2011 11:30:10 GMT+0200}
Date {Tue Dec 06 2016 11:30:10 GMT+0100}
as you can see, it also incremented the month and Day.
What am I missing?
thanks in advance
You have to set the year only, using the setYear method:
endDate.setYear(endDate.getFullYear() + 5);
Using setDate(getFullYear()+5) you add 5 + (year of the date) days to the date value of endDate
You're adding 2016 days to it, not modifying the year, which is 5 and a half year.

Categories

Resources