Javascript Date Object - Different Value in JSFiddle - javascript

This is a simple one I think.
Why do I get 2015-11-04 when I run the following code in JSFiddle (new Date(1451606399999), but when I run the same code in my browser console I get 2015-12-31 (which is the value I'm expecting).
I would have thought any in either case the timezone would be the same as the code is running on the client, and why would timezone make more than a month difference in the date?
function test()
{
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("myDiv").innerHTML = formattedTime;
}
JSFiddle with code

Confusingly, date.getMonth() is 0 based, meaning 0 is January, so it should be month = date.getMonth()+1. Also confusingly date.getDay() actually returns the day of the week (0 is Sunday, 1 is Monday... etc). The function you're looking for is date.getDate()
function test(){
var date = new Date(1451606399999);
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(date);
document.getElementById("myDiv").innerHTML = formattedTime;
}

Related

Formatting time error - "10.03" becomes "10.3"

I have a date and time that I format. It works most of the time, but if the time has a "0" in the second last space it will return wrong. For example, time "10.30" will be formatted correctly, but "10.03" will return "10.3" without the zero.
My code:
const today: Date = new Date();
const date: Date = new Date(item.receivedDateTime);
let time: string;
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = date.getHours() + ":" + date.getMinutes();
} else {
time = date.getDate() + "/" + (date.getMonth() + 1);
}
Above will format time incorrectly. What is wrong in the code? I prefer not to use padstart as it is not supported in IE11 or moment.js.
You can save the value of date.getMinutes() in a variable and check if it's smaller than 10, and if so, append a 0.
const minutes = date.getMinutes();
const formattedMinutes = (minutes < 10) ? '0' + minutes : minutes;
Finally, use the formatted value for output:
time = date.getHours() + ":" + formattedMinutes;
You can use a simple pad function
const pad = num => ("0"+num).slice(-2);
const item = {"receivedDateTime":1570000000000}
const today = new Date();
const date = new Date(item.receivedDateTime);
let time = "";
if (date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate()) {
time = pad(date.getHours()) + ":" + pad(date.getMinutes());
} else {
time = pad(date.getDate()) + "/" + pad(date.getMonth() + 1);
}
console.log(time)
Instead of,
time = date.getHours() + ":" + date.getMinutes();
You can use,
var minutes = d.getMinutes() > 9 ? d.getMinutes() : '0' + d.getMinutes();
time = date.getHours() + ":" + minutes

Why this code got an Uncaught TypeError

I want to get next day and format it into "yyyy-MM-dd HH:mm" format, but when I run this in chrome's console, I got an Uncaught TypeError: date.getHours is not a function, why? The nextDay variable is clearly an instance of Date.
But when I removed hour and minute, just kept year, month and date, it successed, can anyone tell me the reason?
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
date = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));
Your function takes a parameter named "date" and then tries to declare a local variable named "date". That declaration will be ignored, and the initializer will just overwrite the value of the parameter.
Change the name of the parameter:
function format(d) {
var year = d.getFullYear(),
month = d.getMonth(),
date = d.getDate(),
hour = d.getHours(),
minute = d.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
You are using the same variable name as the parameter, date is used twice, change the variable name like down below.
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
theDate = date.getDate(), //change the variable name
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));

How to format database datetime in javascript?

I have a datetime value gotten from an SQLServer database table:
2016-08-16T17:00:00Z
Using javascript, I want to format the date as follow:
16/08/2016 17:00:00
I have used the code below:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}
The result from the sample resource is:
17/71/2016
I want your help to get the output result as: "16/08/2016 17:00:00"
If all you want to do is format it then you don't need to create an actual date object, you can do a simple string replace using a regex to grab the individual parts, as per this simple demo:
var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));
In the context of your function:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
} else {
return value;
}
}
Another solution:
var parsed = Date.parse("2016-08-16T17:00:00Z"),
date = new Date(parsed),
day = date.getUTCDate(),
month = date.getUTCMonth() + 1,
year = date.getUTCFullYear(),
hour = date.getUTCHours(),
minute = date.getUTCMinutes(),
second = date.getUTCSeconds(),
dateStr = "";
day = day < 10 ? "0" + day : day;
month = month < 10 ? "0" + month : month;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
dateStr = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second;
console.log(dateStr);
Updated: The old code may change across countries, because they have different local date/time format, so I have updated to format it explicitly.
Try this
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' +seconds ;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
You can use this library to format the date as you desire with implementing some logic.
http://momentjs.com/
Just work with the function parameter value and use moment.
Example:
const date = moment("2016-08-16T17:00:00Z").date();
const month = moment("2016-08-16T17:00:00Z").month();
const hour = moment("2016-08-16T17:00:00Z").hour();
const year = moment("2016-08-16T17:00:00Z").year();
const minute = moment("2016-08-16T17:00:00Z").minute();
const sec = moment("2016-08-16T17:00:00Z").second();
// implementing some logic
console.log('' + date + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + sec);
here is the fiddle:
https://jsfiddle.net/Refatrafi/6m4m7mp3/

Javascript Add minutes to date not working in IE and Safari

I want to add minutes to a date and display it.I am using the following code
function dt(){
var d = new Date();
d.setMinutes(d.getMinutes()+15*60);
var theDate = d.getFullYear() + '-' + ( d.getMonth() + 1 ) + '-' + d.getDate()+' '+d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
//var d1 = new Date( Date.parse( theDate ) + s1*60*1000 );
var d1=new Date(theDate);
var hours = d1.getHours();
var minutes = d1.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ';
var t=( d1.getMonth() + 1 )+ '/' + d1.getDate() + '/' + d1.getFullYear() +' '+strTime; alert(t+ampm);
}
dt();
This code is working fine in Chrome.But in IE and safari, it was returning NAN:NAN:NAN 12:NAN AM.
Anyone please help.
Regards
Rekha
The line:
d.setMinutes(d.getMinutes()+15*60);
will add 15 hours to the date. Why not:
d.setHours(d.getHours()+15);
Then you copy a date by creating a string then parsing it:
var theDate = d.getFullYear() + '-' + ... + d.getSeconds();
var d1 = new Date(theDate);
Do not do that. Ever. Parsing date strings is unreliable (as you've discovered) and not recommended. To copy a date, use:
var d1 = new Date(+d);
Try replacing:
var d1 = new Date(theDate);
with:
var d1 = new Date(d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());
Using the Date contructor with a date string has some limitations

javascript date + 7 days

What's wrong with this script?
When I set my clock to say 29/04/2011 it adds 36/4/2011 in the week input! but the correct date should be 6/5/2011
var d = new Date();
var curr_date = d.getDate();
var tomo_date = d.getDate()+1;
var seven_date = d.getDate()+7;
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
var tomorrowsDate =(tomo_date + "/" + curr_month + "/" + curr_year);
var weekDate =(seven_date + "/" + curr_month + "/" + curr_year);
{
jQuery("input[id*='tomorrow']").val(tomorrowsDate);
jQuery("input[id*='week']").val(weekDate);
}
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.
Without declaration
To return timestamp
new Date().setDate(new Date().getDate() + 7)
To return date
new Date(new Date().setDate(new Date().getDate() + 7))
Something like this?
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
convert to date again:
date = new Date(res);
alert(date)
or alternatively:
date = new Date(res);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds;
alert(formattedTime)
In One line:
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
$('#txtEndDate').val(output);
var future = new Date(); // get today date
future.setDate(future.getDate() + 7); // add 7 days
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();
console.log(finalDate);
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Two problems here:
seven_date is a number, not a date. 29 + 7 = 36
getMonth returns a zero based index of the month. So adding one just gets you the current month number.

Categories

Resources