Javascript Converting Ints to Time? - javascript

For a project app I'm making, a homework keeper, I need to be able to turn a number like 10 into a month like october, then do this with year, month, day, and time. Then I need to save it all in a date. How do I do this? I have been looking everywhere and cannot find how to do it.

It looks like you're looking for the Date() constructor.
var month = 10;
var day = 17;
var year = 2017;
var hour = 8;//Use the 24 hour clock for times in the PM
var minutes = 36;
var date = new Date(year, month-1, day, hour, minutes);//Outputs October 17th, 2017 at 8:36am in your local timezone
You have to subtract 1 from the month because January starts at 0, not 1.
Alternatively, I like to use moment.js for the flexibility depending on use, so you could instantiate it like this:
var date = moment(year + '-' + month + '-' + day + ' ' + hour + ':' + minutes, 'YYYY-M-D H:m');//Because you are using numbers/integers, none of them will have preceding zeroes

Take a look at the Date constructor - I think it doesn everything you need.
Your biggest gotcha is that months are 0-indexed so you'll actually turn 9 into October. Also beware that if you don't initialise Date with anything, it'll assume you mean now.
var date = new Date();
date; // -> Tue Oct 17 2017 13:34:49 GMT+0100 (GMT Daylight Time)
date.setMonth(10); // -> 1510925689970
date; // -> Fri Nov 17 2017 13:34:49 GMT+0000 (GMT Standard Time)

Related

Subtracting 1 month to 2015-12-31 gives 2015-12-01

I'm trying to subtract one month from 2015-12-31 but it gives me 2015-12-01 instead of 2015-11-30. Why ?
Code:
var date1 = new Date('2015-12-31');
var date2 = new Date(date1);
date2.setMonth(date1.getMonth() - 1);
console.log(date1);
console.log(date2);
Output:
Thu Dec 31 2015 01:00:00 GMT+0100 (CET)
Tue Dec 01 2015 01:00:00 GMT+0100 (CET)
Any workaround?
When subtracting months, you can check whether the day of the adjusted Date is different to the day of the initial Date. If it is, then it must have rolled over to the next month, so set the day of the adjusted Date to 0, so it goes to the last day of the previous month, e.g.
function subtractMonths(date, months) {
var day = date.getDate();
date.setMonth(date.getMonth() - months);
if (date.getDate() != day) date.setDate(0);
return date;
}
// 31 Mar 2016 - 1 month = 29 Feb 2015
[[new Date(2016,2,31), 1],
// 29 Feb 2016 - 12 months = 28 Feb 2015
[new Date(2016,1,29), 12],
// 15 Feb 2016 - 3 months = 15 Nov 2015
[new Date(2016,1,15), 3]].forEach(function(arr){
document.write('<br>' + subtractMonths(arr[0], arr[1]));
})
The same algorithm can be used for adding months. Note that this is why date arithmetic is not symmetric, e.g.
31 May + 1 month => 30 June
30 June - 1 month => 30 May
i.e. If A + B = C, then C - B = A may or may not be true (and vice versa).
Try this
var date1 = new Date('2015-12-31');
var date2 = new Date(date1);
date2.setDate(date2.getDate()-date1.getDate());
alert(date2)
Per the setMonth documentation, ‘If you do not specify the [optional] dayValue parameter, the value returned from the getDate() method is used’. Since you’re not specifying the optional parameter, your code tries to set the date to 2015-11-31, which isn’t valid. JavaScript resolves this situation by setting the date to one day after 2015-11-30, which is 2015-12-01.
As for a workaround, it depends on what you’re actually trying to do. Are you trying to go 31 days back from 31 December? Or are you trying to get the last day of the month before December? Date semantics are extremely complicated; what are you going to do when the inevitable edge cases arise?
It is producing the requested result, which is subtracting 1 month from the date given. But remember a month is a variable amount of time. November 31 is actually December 1 (just like November 55th would actually be December 25, Christmas). To get the last day of the previous month you could do something like this:
var date = new Date('2015-12-31');
date.setDate(-1)

Get start and end day of week considering year starting in the middle of week [duplicate]

This question already has answers here:
How to get first and last day of the current week in JavaScript
(32 answers)
Closed 7 years ago.
I was using a function to return me the start and end day of a given week number from the year. Here is the function:
function getWeekRange(week){
var d = new Date("Jan 01, " + $scope.today.getFullYear() + " 01:00:00");
var w = d.getTime() + 604800000 * (week);
var d1 = new Date(w);
var d2 = new Date(w + 518400000);
return {
startDate: d1,
endDate: d2,
};
}
I set the year dynamically, and let's see an example where the year is 2015. Considering the week number starting by 0, if I use getWeekRange(0) I will receive the following result:
{
startDate: Thu Jan 01 2015 01:00:00 GMT-0200 (BRST),
endDate: Wed Jan 07 2015 01:00:00 GMT-0200 (BRST)
}
The problem is that this code does not consider the year of 2015 starting on a Thursday. The correct result for getWeekRange(0) should be:
{
startDate: Thu Jan 01 2015 01:00:00 GMT-0200 (BRST),
endDate: Sat Jan 03 2015 01:00:00 GMT-0200 (BRST)
}
and the result for getWeekRange(1) should be:
{
startDate: Sun Jan 04 2015 01:00:00 GMT-0200 (BRST),
endDate: Sat Jan 10 2015 01:00:00 GMT-0200 (BRST)
}
Does anyone have a clue?
-- EDIT --
My question is different from this one, because I don't have a given day of the year, I have only a week number of the year (from 0 to 51), and my case considers that the first week of the year is only a part of a full week, as mentioned by likeitlikeit.
I could find a simple solution for my question, since only the first week of my year could cause me problems. Here is the code:
function getWeekRange(week){
var d = new Date("Jan 01, " + $scope.today.getFullYear() + " 01:00:00");
var firstWeekDays = 7 - d.getDay();
var d1, d2;
if(week > 0) {
var w = d.getTime() + 604800000 * (week-1) + 24*60*60*1000 * firstWeekDays;
d1 = new Date(w);
d2 = new Date(w + 518400000);
} else {
d1 = d;
d2 = new Date(d1.getTime() + 24*60*60*1000 * (6 - d1.getDay()));
}
return {
startDate: d1,
endDate: d2,
};
}
There are 2 main diferences from the initial code.
For the week of the year I simply get the initial day of the year, and then based on the day of the week it starts I can find the end day of the week
For the other weeks, I sum 7*week-1 days to initial day (this sum does not consider the number of days of the first week), and also add firstWeekDays which is the number of days of first week (because it is not always 7 as the other weeks).
If anyone has a better solution, I will be glad to listen.
This answer shows how to get the first day of a week using getDate to calculate the offset from the current day.
Using this method, you can use getDate to determine which day of the week the first day of the year falls on. You can then subtract the last day of the week from this value to know how many days to add to your d2 in order to compute the date for Saturday by adjusting your date from the first day of the year + the offset in days till the end of the week for Jan 1.

DateTime new Date(params) in javascript is faster by 1 month

It is very weird but it seems that new Date(params), when passed in the correct format of year, month, day, hours, minutes, seconds, milliseconds, it is ahead by 1 month.
Take a look at the following implementation:
// The format below needs to be changed according to req.param('dateTime')
// dateTime format is as follows: "dd/MM/yyyy HH:mm:ss"
var dateTime = report['dateTime'];
console.log('dateTime: '+dateTime);
var dateTimeSplit = dateTime.split(' ');
var dateSplit = dateTimeSplit[0].split('/');
var timeSplit = dateTimeSplit[1].split(':');
var day = parseInt(dateSplit[0]);
var month = parseInt(dateSplit[1]);
var year = parseInt(dateSplit[2]);
var hour = parseInt(timeSplit[0]);
var minute = parseInt(timeSplit[1]);
var second = parseInt(timeSplit[2]);
var createdAt = new Date(year, month, day, hour, minute, second, 0);
console.log('createdAt: '+createdAt);
And the results from the logs are:
Feb 09 04:13:46 sails-wusrs app/web.1: createdAt: Mon Mar 09 2015 12:02:24 GMT+0000 (UTC)
Feb 09 04:13:46 sails-wusrs app/web.1: dateTime: 09/02/2015 12:02:24
This server is running on heroku and it's weird that the log of createdAt is in front of dateTime. Everything else is alright, except for the month. 02 is Feb right? I'm so confused. Thanks for any help!
Month in javascript datetime starts from 0.
http://javascript.info/tutorial/datetime-functions

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.
startdate=document.getElementById("jscal_field_coverstartdate").value;
now I want to add 11 month from the above startdate. How to do that.
date format = 2013-12-01
Without the date format it is difficult to tell, however you can try like this
add11Months = function (date) {
var splitDate = date.split("-");
var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
newDate.setMonth(newDate.getMonth() + 11);
splitDate[2] = newDate.getDate();
splitDate[1] = newDate.getMonth() + 1;
splitDate[0] = newDate.getFullYear();
return startdate = splitDate.join("-");
}
var startdate = add11Months("2013-12-01");
alert(startdate)
JSFiddle
If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:
var date = new Date("2013-12-01");
console.log(date);
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));
console.log(new Date(newdate));
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)
In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.
You can do it like this:
var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)
Try this:
baseDate.setMonth(2);
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) { sum.setDate(0); }
var m = newDate.getDate();
var d = newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);
Notes:
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months.
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

What's wrong on adding Days at this Date function?

This is my code:
var dat = new Date("24/03/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
but it print Tue Jan 06 2015 00:00:00 GMT+0100?
The date is wrong: should be 31/03/2013 (and I'd like to print it in this format).
My browser (Chrome) prints "Invalid date", but apparently yours interprets the initializing date in mm/dd/yyyy format instead of dd/mm/yyyy. Therefore it thinks it's the 3rd day of the 24th month of 2013, which is January 3rd, 2015.
I'm not sure why it would print it as January 6th if you add 7 days to it.
The safest way is to give the numbers explicitly:
var dat = new Date( 2013, 2, 24 );
Change the format of your date to put the day after the month:
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
console.log(dat)
For me this returns:
Sun Mar 31 2013 00:00:00 GMT+0000 (GMT Standard Time)
You should have to give the month number first. Then you'll get the correct answer
Try this code
var dat = new Date("03/24/2013");
dat.setDate(dat.getDate() + 7);
var curr_date = dat.getDate();
var curr_month = dat.getMonth() + 1; //Months are zero based
var curr_year = dat.getFullYear();
console.log(curr_date + "/" + curr_month + "/" + curr_year);
You should print out your date before you add seven. I suspect it's being set to the 3rd day of the 24th month in 2013, which equates to somewhere close to January 2015.
That's why you're getting a date well advanced from the current one. Why it's giving you the 6th of January rather than the 10th, I'm not sure, but you can probably fix it just by changing your input string to the US format of mm/dd/yyyy, or using a more explicit constructor that's not subject to misinterpretation:
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
try this!!!
var aDate = new Date(2013,3,24);
aDate.setDate(aDate.getDate() + 7);
var dateString = aDate.getDate() + "-" + aDate.getMonth() + "-" + aDate.getFullYear();
alert(dateString);

Categories

Resources