This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Changing the format of a date string
(2 answers)
Closed 5 years ago.
I am trying to use a simple date function in my application to pass a date in the format of yyyy-mm-dd such as 2017-07-30 and have it returned in the format of 07/30/2017.
However, when I try this, I supply my date correctly but it outputs one day shorter than what I am looking for.
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
var day = date.getDate().toString();
var month = (date.getMonth() + 1).toString();
// Months use 0 index.
return (month[1] ? month : '0' + month[0]) + '/' +
(day[1] ? day : '0' + day[0]) + '/' +
date.getFullYear();
}
}
console.log(format('2017-07-30'));
Here is a fiddle: http://jsfiddle.net/49pptrj4/
Any thoughts as to why this is returning incorrectly?
Result on my end:
From here
Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.
Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.
The following code should work for creating a Date in the local timezone with the correct date.
utcDate = new Date("2017-07-30"); //Date object a day behind
new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date
Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.
This might not work in areas ahead of UTC; it might advance an extra day.
Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.
Related
This question already has answers here:
Is the Javascript date object always one day off?
(29 answers)
Closed 2 years ago.
I have found many examples on the internet of converting from seconds or milliseconds to a JavaScript Date, but only a few for converting from days to a Date object. When I tried these examples in my own code (with my own values), I was unable to replicate their results.
My API returns an integer value representing days since UNIX epoch. I need to find a way to convert this to a JavaScript date object, so that I can display it in a human readable format.
For example:
new Date(18521 * 86400 * 1000)
// multiply by 86400 (seconds in a day), then by 1000 to convert to milliseconds.
At the time of writing, the date is 9/17/2020 MMDDYYYY, and 18522 days have passed since UNIX epoch. However, when I try to retrieve yesterday's UNIX date 18521 using the date constructor with some math (mentioned above), I get the incorrect date: Sep 15 2020. I would expect to get (Sep 16 2020) since I have only subtracted one day, but for some reason that is not the case.
Is there anything I am doing incorrectly here? What should I change to make my code work?
The way you're doing it is correct. There are always 8.64e7 ms in an ECMAScript UTC day and ECMASCript and Java have the same epoch. The way you're doing it sets the UTC date to the correct value (which is the right way to do it), not the local date. The default toString shows the local date so if the host is set to a negative offset, it will show one day earlier.
So get the UTC date instead:
new Date(18521 * 8.64e7).toISOString() //2020-09-16T00:00:00.000Z.
If you want to do this with a local date, then create a date for Jan 1970 and set the "date" parameter to the day count plus 1 (because January starts on 1 not 0):
console.log('UTC : ' + new Date(18521 * 8.64e7).toISOString() +
'\nLocal: ' + new Date(1970, 0, 18521 + 1).toDateString());
This question already has answers here:
Add one day to date in javascript
(11 answers)
Closed 4 years ago.
I have From-Date, To-Date, and Total-Days...if i have a From-Date and Total-Days then i have to calculate To-Date automatically
I Used The Following method to get the To-Date day
var FromDate = $("#FromDate").val();
var TotalDays = $("#txtDays").val();
FromDate.setDate(parseInt(FromDate.getDate()) + parseInt(NoOfDays));
var dd = FromDate.getDate()-1;
This Will Not Work For Day 1 of every month.....Since It Returns 0
How To Handle This Situation or help me to solve this in another way....Thanx In Advance
try this
var d = new Date('08-20-2018');
d.setDate(d.getDate() - 1);
alert(d.getDate());
Date object is smart enough to know what to do if you set any of the "components" (month, day, hour, minute, second, millisecond) outside of "normal" range - it does the maths for you
If you only need to know the previous date, you can always subtract the 24hours from the epoch time and then convert it back to date object and get the date like:
new Date(new Date('08-01-2018').getTime() - 24*3600000).getDate()
new Date('08-01-2018').getTime() will give you the epoch time of the date you want previous date from
24*3600000 is subtracting the 24 milliseconds from the epoch
After subtracting the value you get the previous day epoch and using the new Date() constructor you are getting the Date object again
On this new date object you can call getDate() method to get the correct result of 31.
I have given date to Date constructor in MM-DD-YYYY format
This question already has answers here:
Generating a date in a particular timezone [duplicate]
(2 answers)
Converting unix date-timestamp to time for a particular timezone in javascript
(2 answers)
Closed 5 years ago.
I have UTC time 1502212611. I have to convert it to 2017-08-08 17:16:51. But when I use the code below I am getting 2017-08-08T17:16:51.000Z.
var utc = 1502212611;
var utcSeconds = utc;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
console.log(d);
You can use moment.js, as others have already suggested.
But in your question is not clear if you want the output as UTC or IST (the question title says "Convert UTC to IST", but in the question the desired output (2017-08-08 17:16:51) is the corresponding UTC date/time).
Anyway, if you want the output in UTC, you can do this:
var utc = 1502212611;
var m = moment.unix(utc).utc().format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The unix method takes a value of seconds since epoch (1970-01-01T00:00Z). Then the utc() method makes sure the date will be formatted as UTC (if you don't call it, the date will be displayed using the default timezone, which can vary according to your system).
The output will be:
2017-08-08 17:16:51
If you need to convert to IST, you'll need to also use moment timezone:
var utc = 1502212611;
var m = moment.unix(utc).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The tz method converts the date to another timezone. The rest of the code is similar to the previous one.
The output will be:
2017-08-08 22:46:51
Note that I used Asia/Kolkata instead of IST. That's because the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard - IST can be "India Standard Time", "Israel Standard Time" or "Irish Standard Time", and the API can't deal with such ambiguity (the code above won't work with IST, so you must use a proper timezone name).
You can get a list of all available timezones names (and choose the one that fits best to your case) by calling moment.tz.names().
In plain Javascript, you must do it manually:
// pad zero if value <= 9
function pad(value) {
return value > 9 ? value: "0" + value;
}
var utc = 1502212611;
var d = new Date(0);
d.setUTCSeconds(utc);
var m = d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate())
+ ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes())+ ':' + pad(d.getUTCSeconds());
console.log(m);
Output:
2017-08-08 17:16:51
You can use moment if you have a moment .
momenttime = moment()
momenttime.format("YYYY-MM-DD hh:mm:ss ")
have problem for format date in JavaScript, this is my function code
//originalDate = '2016-03-02 09:12:14.989522';
var d = new Date(originalDate),
month = d.getMonth() + 1,
day =d.getDate(),
year = d.getFullYear(),
hour = d.getHours(),
min = d.getMinutes();
alert([day, month, year].join('-')+' '+[hour,min].join(':'));
and my original date ='2016-03-02 09:12:14.989522';
and my code always return 'Nan-Nan-Nan Nan:Nan', It's seen unknown originalDate that I pass to.
any help?
Note: datatype in database of date of mine is timestamp
Simple solution: Replace the space in your date string with a "T".
(However, to be completely technically correct, you should also include a time zone indicator at the end, either an additional "Z" to indicate UTC, i.e. Coordinated Universal Time, or "+hh:mm" or "-hh:mm" to indicate a time zone offset.)
The MDN site for Date.parse() writes:
Because of the variances in parsing of date strings, ...results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.
and
The date time string may be in ISO 8601 format.
The ISP 8601 specs referred to above writes:
The formats are as follows. Exactly the components shown here must be present, with exactly this punctuation. Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO 8601.
and
Complete date plus hours, minutes, seconds and a decimal fraction of a
second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
Here is your code re-written replacing the space in date with a "T". If that doesn't work in your browser, add a "Z" or time zone offset at the end of date.
var date ='2016-03-02T09:12:14.989522';
var d = new Date(date),
month = d.getMonth() + 1,
day = d.getDate(),
year = d.getFullYear(),
hour = d.getHours(),
min = d.getMinutes();
document.write([day, month, year].join('-') + ' ' + [hour, min].join(':'));
Is the date parameter in your code a Date object? That won't work. There is no such constructor in Javascript. You could use date.now() though.
Check here for the valid constructors for Date https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date
First parse your original date then use it in your code.
var MilliSecond=Date.parse(originalDate);
var d=new Date(MilliSecond),
month=d.getMonth()+1,
day=d.getDay(), .......
I want to get the date and time from 2 text boxes and format them and send them to the Google directions javascript API to get transit directions.
How do I add the date and time values together and then convert them to standard UTC time?
This is what i have:
var dateOfTravel = document.getElementById('fdate').value;
var timeOfTravel= document.getElementById('ftime').value;
//join the date and time strings
var d1 = new Date(dateOfTravel + ' ' + timeOfTravel);
alert("date and time is " + d1);
alert(d1.getTime());
var UTCDateAndTime = moment(d1).unix();
alert(UTCDateAndTime);
thanks,
Tom
Several options:
JavaScript dates have toISOString, which provides a standard ISO-8601 date/time string always in UTC, e.g. "2015-10-25T11:02:23.019Z". (Yes, the timezone specifier is always Z, that's required by the spec. So it doesn't vary by locale or timezone.)
You can use the various getUTCXyz methods to build your own string.
getTime returns the number of milliseconds since The Epoch (Jan 1 1970 at midnight UTC), which is not timezone-dependent.
getTimezoneOffset tells you how far offset you are from UTC, which you could use to adjust things (though I can't see a good reason for that in this case).
This appears to be working:
var d1 = new Date(dateOfTravel + ' ' + timeOfTravel);
//if the year is less than 1970 then add 100 on. Using 2 digit years and there's a bug with javascript date implimentation
if (d1.getFullYear() < 1970) {
d1.setFullYear(d1.getFullYear() + 100);
}