Everything works fine except for 1 date. This is my function.
export function formatDate(date) {
console.log(new Date(date), date);
let d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getUTCDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [month, day, year].join('/');
}
I tried to log it in console and this is the result.
I have underlined the wrong date. It says may 1 eventhough its april 30. This is probably caused by the timezone. Does it mean that new Date().getMonth() can't be trusted?
Your dates are UTC (indicated by the Z at the end of the time string), but you are outputting them in your local timezone (Philippine Standard Time) which is GMT+0800, hence the difference in outputs (which you'll notice is exactly 8 hours). This is caused by your console.log
calling Date.toString() on the result of new Date(date), which outputs the datetime according to the client timezone.
If you want to get the same result as your SQL date, use Date.toUTCString() instead:
let d = new Date('2021-04-30T21:30:15.697Z')
console.log(d.toString())
console.log(d.toUTCString())
Similarly, you need to use Date.getUTCMonth() and Date.getUTCFullYear() to get the correct month from the SQL date:
let d = new Date('2021-04-30T21:30:15.697Z')
console.log(d.getMonth())
console.log(d.getUTCMonth())
Related
Does NodeJS/JavaScript uses the server date?
I have a script in my NodeJS where I format the date before inserting it in the MySQL database.
const today = new Date();
const formattedDate = (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('-');
}
Then I run whenever I want to insert it: '${formattedDate(today)}'
However, I notice it is saving the wrong date. Not today's date. Does NodeJS get the server date?
Your today variable is a constant assigned once to today's date when the program is first run (or actually when this file is imported). So if your problem is that you don't get today's date several days after starting the program, this is why. Just call new Date() every time you need today's date, or make today into a function.
I have some code, that is doing pretty much all i need it to do. Its calculating 3 days in the future, excluding dates, and then displaying my "estimated dispatch date"
The date, however displays in full date and time, instead of just date.
Day Month Date Year 12:02:57 GMT+0100 (British Summer Time)
Can anyone help with the code below, so that it excludes local time and only displays the future date, excluding weekend, DD/MM/YYYY or, in the below format;
Monday 20th June
Thanks in advance!
function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
document.write ('Estimated Dispatch Date: ' + addDates(today,daysToAdd));
You can use the toDateString method to display just the date portion of your Date object, but you will need to use a few other methods for full control over the format of your date string...
You can display just the date, month and year parts of your local date and time with a few extra lines of code using the getDate, getMonth, and getFullYear methods to help with the formatting. You could try passing specific formatting parameters to toLocaleString, but this may display different results in different browsers. For example, the code below outputs a date in the format dd/mm/yyyy in Chrome but that output is not guaranteed across browsers.
new Date().toLocaleString('en-GB', {year: 'numeric', month: 'numeric', day: 'numeric'})
Not sure I am following how you want to handle weekend dates, so the below handles the date formatting that you want in the formatDate function separately from the addDays function where it just handles weekend dates by rolling the date forward to a Monday if the initially calculated date lands on a Saturday or Sunday.
// format input date to dd/mm/yyyy
const formatDate = (date) => {
const d = date.getDate(); // day of the month
const m = date.getMonth(); // month index from 0 (Jan) to 11 (Dec)
const yyyy = date.getFullYear(); // 4 digit year
const dd = (d < 10 ? '0' : '') + d; // format date to 2 digit
const mm = (m + 1 < 10 ? '0' : '') + (m + 1); // convert index to month and format 2 digit
return `${dd}/${mm}/${yyyy}`;
};
// add input days to today and adjust for weekend output
const addDays = (today, days) => {
const now = today.getTime() // now in UTC milliseconds
const ms = 24 * 60 * 60000; // milliseconds in one day
const date = new Date((days * ms) + now); // today plus input days
const day = date.getDay(); // weekday index from 0 (Sun) to 6 (Sat)
// adjust weekend results to next weekday
if (day === 0 || day === 6) {
let adj = day === 0 ? 1 : 2;
return new Date(((days + adj) * ms) + now);
}
return date;
};
document.write('Estimated Dispatch Date: ' + formatDate(addDays(new Date(), 3)));
The following returns 11 which is correct.
var month = d.getMonth();
alert(month);
When I try adding a month to it returns something very different
var month = d.setMonth(d.getMonth() + 1);
alert(month);
It returns: 1513230546878
Return values of methods that you are using in your code are as follows
d.getMonth() - A Number, from 0 to 11, representing the month (Link)
d.setMonth() - A Number, representing the number of milliseconds between the date object and midnight January 1 1970 (Link)
Please note, d.setMonth() will modify your Date object in place. So, if you want your code to work as expected, you can write as follows
var d = new Date()
var month = d.getMonth();
alert(month);
d.setMonth(d.getMonth() + 1);
alert(d.getMonth());
d.setMonth() method returns the updated timestamp value (See docs). That's why you got a long number.
If you want to get the month you will use as per below
var d = new Date("2017-10-03");
d.setMonth(d.getMonth() + 1);
var month = d.getMonth(); // get new month
alert(month);
hope it helps
In java script, if you write this:
var month = d.setMonth(d.getMonth() + 1);
You get a timestamp. Meaning, an integer number representing the month you chose.
This is because, setDate accepts a dayValue parameter:
Date.setDate(dayValue)
Meaning that:
var dt = new Date("Aug 28, 2008 23:30:00");
dt.setDate(24);
console.log(dt);
will result in:
Sun Aug 24 2008 23:30:00 //+ your standard gmt time
For further inquire, see this Link
//set date to now:
var d = new Date();
console.log(d);
//just checking
var month = d.getMonth();
console.log(month);
//add a month
d.setMonth(d.getMonth() + 1);
//now the month is one ahead:
console.log(d.getMonth());
console.log(d);
I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(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;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed
I'm trying to get one year from now's date, and it's not working.
JS:
var now = new Date();
var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());
var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());
Output:
one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)
one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)
The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.
If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.
Thanks!
This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().
As setYear() is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)
Use this:
var startDate = new Date();
startDate.setFullYear(startDate.getFullYear() - 1);
Using some of the answers on this page and here,
I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:
Date.prototype.addYears = function(n) {
var now = new Date();
return new Date(now.setFullYear(now.getFullYear() + n));
};
console.log('Year from now is', new Date().addYears(1));
In very simple way. use this code.
// define function
function nextYearDate(date1) {
var date2 = new Date(date1);
var date3 = date2.setDate(date2.getDate() - 1);
var date = new Date(date3);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear()+1;
var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
$("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />
<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />