format date using javascript - javascript

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(), .......

Related

Create JavaScript Date object from date string + time string + timezone offset string

I have total 4 different input i.e.:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00) no-matter what my local browser timezone is. The issue is when I combine these strings and I try to make date object using new Date() function, my datetime gets converted into UTC timestamp.
I tried this:
const date =
moment(this.actualDateOfSurgeryDate).format(YYYYMMDD) +
'T' +
moment(this.actualDateOfSurgeryTimeDropDown + ' ' + this.actualDateOfSurgeryTimeAM_PMDropDown, ['h:mm A']).format('HH:mm:ss') +
offsetTime;
this.caseDetail.actualDateOfSurgery = new Date(date);
This gives me output something like: 2020-05-05T04:30:00.000Z
How can I get my desired output: 2020-05-05T15:30:00-09:00 ??
I have moment js available in my project
I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00)
Date objects are extremely simple, they're just a time value that is an offset in milliseconds since 1970-01-01T00:00:00Z, so are inherently UTC. The built–in parser is unreliable and lacks any functionality such as format tokens.
So if you have separate values like:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
then you can create a string that is compliant with the format defined in ECMA-262 and that should be parsed correctly by the built–in parser, e.g.
new Date('2020-05-05T15:30:00.000-09:00')
However, general advice is to avoid the built–in parser due to differences in implementations. Also, the format must be exact (e.g. including seconds and milliseconds in the timestamp, colon (:) in the offset) or some implementations will reject it as malformed and return an invalid date.
Once you have a Date object, getting a "local" timestamp with offset is an issue of formatting, which has been answered many times before (e.g. How to format a JavaScript date). There aren't any decent built–in formatting functions (toLocaleString with options is OK for some purposes but generally lacking in functionality), so you'll have to either write your own function, or use a library.
The following examples use Luxon, which is suggested as the upgrade path from moment.js.
With Luxon, if you specify a representative location, you'll get the offset for that location at the date's date and time. Alternatively, you can fix the offset to a set value, essentially setting it for a timezone without a representative location, so it doesn't have any reference to daylight saving or historic offset changes:
let DateTime = luxon.DateTime;
// Offset per the specified location
let d0 = DateTime.fromISO('2020-01-01', {zone: 'America/Yakutat'});
let d1 = DateTime.fromISO('2020-06-30', {zone: 'America/Yakutat'});
console.log(d0.toString());
console.log(d1.toString());
// Fixed offset per the supplied string
let d2 = DateTime.fromISO('2020-05-05T15:30:00.000-09:00', { setZone: true});
let d3 = DateTime.fromISO('2020-01-01T15:30:00.000-09:00', { setZone: true});
console.log(d2.toString());
console.log(d3.toString());
<script src="https://cdn.jsdelivr.net/npm/luxon#1.24.1/build/global/luxon.min.js"></script>
I get 16:30 due to DST
A date before March or after October will give 15:30
let dateString = "2020-05-05"+"T"+"15:30"+":00"+"-09:00"
console.log(dateString)
const date = new Date(dateString)
console.log(date)
const Anchorage = date.toLocaleString('en-US', {timeZone: 'America/Anchorage', hour12: false})
console.log(Anchorage)
let options = {}
options.timeZone = 'America/Anchorage';
options.timeZoneName = 'short';
console.log(date.toLocaleDateString('en-US'), date.toLocaleTimeString('en-US', options));

Javascript dates are a day off? [duplicate]

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.

Javascript - converting local time to google friendly UTC time

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);
}

Using momentjs to convert date to epoch then back to date

I'm trying to convert a date string to epoch, then epoch back to the date string to verify that I'm providing the correct date string.
var epoch = moment("10/15/2014 9:00").unix(); // do I need to do .local()?
var momentDate = moment(epoch); // I've also tried moment.utc(epoch)
var momentDateStr = momentDate.calendar();
alert("Values are: epoch = " + epoch + ", momentDateStr = " + momentDateStr);
Renders
Values are: epoch = 1413378000, momentDateStr = 01/17/1970
Note: I'm using the following version of the moment js script, //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment-with-locales.js
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local() or .utc().
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
http://momentjs.com/docs/#/displaying/unix-timestamp/
You get the number of unix seconds, not milliseconds!
You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.
moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

How to assume local time zone when parsing ISO 8601 date string?

I have a ISO date string as below
var startTimeISOString = "2013-03-10T02:00:00Z";
when I convert it to date object in javascript using below code, it returns
var startTimeDate = new Date(startTimeISOString);
output is
Date {Sun Mar 10 2013 07:30:00 GMT+0530 (India Standard Time)}
It sure converts the ISOString to date but it converts to local time since new Date() is client dependent. How to just convert iso date time string to date and time but not to local date-time..?
Thanks
According to MDN:
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time
zone, but given an ISO format such as "2014-03-07" it will assume a
time zone of UTC. Therefore Date objects produced using those strings
will represent different moments in time unless the system is set with
a local time zone of UTC. This means that two date strings that appear
equivalent may result in two different values depending on the format
of the string that is being converted (this behavior is changed in
ECMAScript ed 6 so that both will be treated as local).
I have done like this and am now getting the exact time which is inside the ISO date string instead of the local time
var startTimeISOString = "2013-03-10T02:00:00Z";
var startTime = new Date(startTimeISOString );
startTime = new Date( startTime.getTime() + ( startTime.getTimezoneOffset() * 60000 ) );
This will give the same date time inside iso date string , the output here is
o/p
Date {Sun Mar 10 2013 02:00:00 GMT+0530 (India Standard Time)}
To sum up the conversation from tracevipin's post:
All Date objects are based on a time value that is milliseconds since 1970-01-01T00:00:00Z so they are UTC at their core. This is different to UNIX, which uses a value that is represents seconds since the same epoch.
The Date.prototype.toString method returns an implementation dependent string that represents the time based on the system settings and timezone offset of the client (aka local time).
If a UTC ISO8601 time string is required, the Date.prototype.toISOString method can be used. It's quite easy to write a "shim" for this methods if required.
Lastly, do not trust Date.parse to parse a string. Support for an ISO8601 format UTC string is specified in ES5, however it's not consistently implemented across browsers in use. It is much better to parse the string manually (it's not hard, there are examples on SO of how to do it) if wide browser support is required (e.g. typical web application).
Simple ISO8601 UTC time stamp parser:
function dateObjectFromUTC(s) {
s = s.split(/\D/);
return new Date(Date.UTC(+s[0], --s[1], +s[2], +s[3], +s[4], +s[5], 0));
}
and here's a shim for toISOString:
if (typeof Date.prototype.toISOString != 'function') {
Date.prototype.toISOString = (function() {
function z(n){return (n<10? '0' : '') + n;}
function p(n){
n = n < 10? z(n) : n;
return n < 100? z(n) : n;
}
return function() {
return this.getUTCFullYear() + '-' +
z(this.getUTCMonth() + 1) + '-' +
z(this.getUTCDate()) + 'T' +
z(this.getUTCHours()) + ':' +
z(this.getUTCMinutes()) + ':' +
z(this.getUTCSeconds()) + '.' +
p(this.getUTCMilliseconds()) + 'Z';
}
}());
}
This happens because date is printed using toString method which by default returns the date and time in local timezone. The method toUTCString will give you the string you need.
Date actually keeps the date as unix time in milliseconds and provides methods to manipulate it.
In vanilla javascript there isn't a way to create a date that assumes the local time of the ISO formatted string you give it. Here's what happens when you pass an ISO 8601 formatted string to javascript. I'm going to use a non UTC time as it illustrates the problem better than using an ISO formatted string:
var startTime = new Date("2013-03-10T02:00:00+06:00"). Note this could also be 2013-03-10T02:00:00Z or any other ISO-formatted string.
read the time, apply the offset and calculate milliseconds since 1970-01-01T00:00:00Z
You now have only milliseconds - you have lost all timezone info. In this case 1362859200000
All functions, apart from the ones that give you a UTC representation of that number, will use the timezone of the computer running the code to interpret that number as a time.
To do what the original poster wants, you need to.
parse the ISO string, interpret the offset ('Z' or '+06:00') as the timezone offset
store the timezone offset
calculate and store the ms since epoch, using the offset timezone offset
hold that offset
whenever attempting to make a calculation or print the date, apply the timezone offset.
This isn't trivial, and requires a complete interpretation of the 8601 spec. Way too much code to put here.
This is exactly what moment.js is designed to do. I strongly recommend using it. Using moment.js:
moment("2013-03-10T02:00:00Z").format()
"2013-03-10T02:00:00Z"
this will result in printing the ISO time of the original string, preserving the offset.
you can try moment js library https://momentjs.com
For my case, I had 2022-10-17T01:00:00 on my database. SO I need to format it to the 01:00:00 AM.
So here was my solution.
var date = "2022-10-17T01:00:00"
var timeFormat = moment(date ).format('HH:mm A');
output: 01:00:00 AM
it will return ISOdate
var getDate = () => {
var dt = new Date();
var off = dt.getTimezoneOffset() * 60000
var newdt = new Date(dt - off).toISOString()
return newdt.slice(0, 19)
}
Output

Categories