Javascript Date inconsistency - javascript

On my node server, I receive time value from the client in epoch format (milliseconds since Jan 1 1970). I feed it into the Date() object and print it like so:
var d = new Date(epochTime);
var year = d.getFullYear();
var mo = d.getMonth();
var day = d.getDay();
console.log("ISO:" + d.toISOString() + " year:" + year + " mo:" + mo + " day:" + day);
Now, I get weird inconsistency from the date object.
E.g. for the value of "1437386620207.58" - this is what above console.log prints:
ISO:2015-07-20T10:03:40.207Z year:2015 mo:6 day:1
Huh? Why are those dates so different?

Two problems in your code:
Months are zero-based in Javascript, i.e. 0 is January and 11 is December.
getDay() returns the day of the week. That should be getDate() instead to return the day of the month.

Related

JavaScript Date returns different values when the components are separated

I have a date that I want converted to a number in the format of yyyymmdd.
it comes in as
2017-08-16T05:47:42.070Z
I convert it as
let dt = new Date(dte)
which creates the date in dt of:
Wed Aug 16 2017 15:47:42 GMT+1000 (E. Australia Standard Time)
Now when I look at the parts I get the following:
dt.getFullYear() = 2017
dt.getMonth() = 7
dt.getDay() = 3
How come the day and month are off?
getMonth()
returns an integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on.
getDay()
returns an integer number corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
This means that result of your code is correct
dt.getFullYear() = 2017
dt.getMonth() = 7
dt.getDay() = 3
There is a function called getDate() that will return 16 for your case.
These functions are from native javascript Date Object.
You can do it like this:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate("2017-08-16T05:47:42.070Z"));
Following code return result for you:
var dte = '2017-08-16T05:47:42.070Z';
var dt = new Date(dte);
var myFrmt = dt.getFullYear().toString() + (dt.getMonth()+1).toString() + dt.getDate().toString();
alert(myFrmt);
Found out an easy way (don't know why the above doesn't work!!) using Moment
Moment(dt).format('YYYYMMDD').toString()
gives the answer: 20170816 !!

Javascript date backward

I'm trying to compute the date of the day before using:
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
It seems to work well when printed out using:
document.write(nda);
The output is:
Thu Nov 24 2016 00:00:00 GMT+0000 (WET)
which is correct, but when I do:
document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());
I get a wrong output:
2016-10-4
Any suggestion?
You need to do nda.getMonth() + 1.
Months start from 0 so in order to get the right number of the month you must add 1.
Also you need to use getDate() instead of getDay(). getDay will give you the day of the week, while getDate will give you the day of the month.
The end result would be:
nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
document.write((nda.getFullYear())+
"-"+(nda.getMonth()+1)+
"-"+(nda.getDate()));
Date.getMonth() returns the index of the month, which is 0-indexed (So 0 is January, and 11 is December). To correct for this, you add 1.
Date.getDay() returns the day of the week, which is also 0-indexed starting from Sunday (So 4 is Thursday).
Here, you would use Date.getDate() to get the day in the current month (Which is not 0-indexed).
var da = new Date('2016-11-25'),
nda = new Date(da-86400000);
document.write(nda.getFullYear() + "-" +
(nda.getMonth() + 1) + "-" +
nda.getDate());
There is a fundamental rule wiht parsing dates: do not use the Date constructor or Date.parse (they are equivalent for parsing) to parse date strings. Use a library with a parser or parse it yourself with a simple function.
When using:
var da = new Date('2016-11-25');
the date will be treated as UTC, so if you are in a timezone that is west of Greenwich the local date will be the day before. Note the differences in the following:
console.log('Built-in parse: ' + new Date('2016-11-25').toLocaleString());
console.log('No parse : ' + new Date(2016, 10, 25).toLocaleString());
When you do:
nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay();
as others have said, you should use nda.getMonth() + 1, and you want getDate rather than getDay. However, since you are parsing the date as UTC then getting local values, the previous issue with UTC may mean that the date is one day previous.
To construct a date in the local time zone and avoid parsing errors, set the values directly.
To get the day before any date, simply subtract one day. Don't subtract 24 hours or you'll then get errors over daylight saving boundaries (since those days aren't exactly 24 hours long). e.g.:
/* Format a date as yyyy-mm-dd
** #param {Date} date
** #returns {string}
*/
function formatDate(date) {
return date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
var nda = new Date(2016, 10, 25);
console.log('Created date: ' + formatDate(nda));
nda.setDate(nda.getDate() - 1);
console.log('Previous day: ' + formatDate(nda));

Extract Month or Day or Year from Timestamp

I would like to know how to get a specific date format (date or month or day or year) from a timestamp. I am wanting to use this in a view with Backbone JS
var d = new Date(1397639141184);
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
1.If it's JavaScript Timestamp(i.e., in milliseconds)
var date = new Date(13976391000);
var date = date.getDate(); //returns date (1 to 31) you can getUTCDate() for UTC date
var day = date.getMonth(); // returns 1 less than month count since it starts from 0
var year = date.getFullYear(); //returns year
// You can also use getHours(), getMinutes() and so on
2.If it's database timestamp - example 2013-03-14T02:15:00
var date = new Date('2013-03-14T02:15:00'); // Works in all browsers
var date = new Date('2013-10-18 08:53:14');// works in Chrome & doesn't work in IE/Mozilla
//note that its a string and you use the same above functions to get Date,month & year

Unable to get current date time using javascript

var now = new Date();
var dateString = now.getMonth() + "-" + now.getDate() + "-" + now.getFullYear() + " "
+ now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
here month is not displayed correctly.
Example if output is december it prints november
now.getMonth() +1 would display the correct month.
I am looking for a more better approach.
My application has to choose between two radiobuttons.the first option should return the current system date and time and other returns date and time selected from jsp.
On selecting either of the two options,it should return a date in a specific format to the controller.
getMonth() by definition returns month from 0 to 11.
If you are not used to this, you can change the prototype of a Date object:
Date.prototype.getFixedMonth = function(){
return this.getMonth() + 1;
}
new Date().getFixedMonth(); //returns 12 (December)
new Date("January 1 2012").getFixedMonth //returns 1 (January)
But this is not recommended at all.
Another approach
You can do this too if you want:
Date.prototype._getMonth = Date.prototype.getMonth;
Date.prototype.getMonth = function(){ //override the original function
return this._getMonth() + 1;
}
new Date().getMonth(); //returns 12 (December)
new Date("January 1 2012").getMonth //returns 1 (January)
getMonth() is supposed to return the Month as index from 0 to 11 (0 is January and 11 is December). So, what you're getting is the expected return value.
Here is the Function
function GetTime_RightNow() {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
alert(month + "/" + day + "/" + year)
}

JavaScript date: How to add a year to a string that contains mm/dd?

I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)

Categories

Resources