How to do a date format in Javascript? - javascript

I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help

The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.

Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();

Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first

you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.

Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));

Related

Creating timezone independent dates in Javascript?

This question is related to this question.
So if we construct a date using an ISO string like this:
new Date("2000-01-01")
Depending on what timezone we are in, we might get a different year and day.
I need to be able to construct dates in Javascript that that always have the correct year, day, and month indicated in a string like 2000-01-01, and based on the answer in one of the questions if we use back slashes instead like this:
const d = new Date("2000/01/01")
Then we will always get the right year, day, and month when using the corresponding date API methods like this:
d2.getDate();
d2.getDay();
d2.getMonth();
d2.getFullYear();
So I just wanted to verify that my understanding is correct?
Ultimately I need to be able to create Date instances like this for example:
const d3 = new Date('2010/01/01');
d3.setHours(0, 0, 0, 0);
And the time components should always be zero, and the year, month, and day should be the numbers specified in the string.
Thoughts?
I just did a quick test with this:
https://stackblitz.com/edit/typescript-eztrai
const date = new Date('2000/01/01');
console.log(`The day is ${date.getDate()}`);
const date1 = new Date('2000-01-01');
console.log(`The day is ${date1.getDate()}`);
And it logs this:
The day is 1
The day is 31
So it seems like using backslashes should work ...
Or perhaps using the year, month (0 based index), and day constructor values like this:
const date3 = new Date(2000, 0, 1);
date3.setHours(0, 0, 0, 0);
console.log(`The day is ${date3.getDate()}`);
console.log(`The date string is ${date3.toDateString()}`);
console.log(`The ISO string is ${date3.toISOString()}`);
console.log(`Get month ${date3.getMonth()} `);
console.log(`Get year ${date3.getFullYear()} `);
console.log(`Get day ${date3.getDate()} `);
NOTE
Runar mentioned something really important in the accepted answer comments. To get consistent results when using the Javascript Date API use methods like getUTCDate(). Which will give us 1 if the date string is 2000-01-01. The getDate() method could give us a different number ...
From the ECMA standard of the Date.parse method:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
What is happening is that New Date() implicitly calls Date.parse on the string. The "2000-01-01" version conforms to a Date Time String Format with a missing offset representation, so it is assumed you mean UTC.
When you use "2000/01/01" as input the standard has this to say:
If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
So in short the browser can do what they want. And in your case it assumes you mean the offset of the local time, so whichever offset you are located in gets added when you convert to UTC.
For consistent results, perhaps you want to take a look at Date.UTC
new Date(Date.UTC(2000, 0, 1))
If you need to pass in an ISO string make sure you include the time offset of +00:00 (is often abbreviated with z)
new Date("2000-01-01T00:00:00Z");
If you want to later set the date to something different, use an equivalent UTC setter method (e.g. setUTCHours).
When you retrieve the date, also make sure to use the UTC getter methods (e.g. getUTCMonth).
const date = new Date("2000-01-01T00:00:00Z");
console.log(date.getUTCDate());
console.log(date.getUTCMonth());
console.log(date.getUTCFullYear());
If you want to retrieve the date in a specific format you can take a look at Intl.DatTimeFormat, just remember to pass in timeZone: "UTC" to the options.
const date = new Date("2000-01-01T00:00:00Z");
const dateTimeFormat =
new Intl.DateTimeFormat("en-GB", { timeZone: "UTC" });
console.log(dateTimeFormat.format(date));

How can I convert this string representing a Date into an ISO 8601 compliant using JS?

I am not so into JavaScript and I have the following problem.
I have a JSON object like this:
{
"start_date": "2017-11-09 06:00:00"
}
Into a JavaScript script executed into the browser I do:
var dateCurrentOriginalForecast = new Date(currentOriginalForecast.start_date);
and it works fine: it creates a new Date object with the value related to 2017-11-09 06:00:00 date.
The problem is that I have to perform this JavaScript script into a Java application using Rhino (a JavaScript implementation that allows to perform JS code into a Java application) and here it cause an error:
TID: [-1234] [] [2017-11-09 11:10:08,915] INFO {org.apache.synapse.mediators.bsf.ScriptMessageContext} - dateCurrentOriginalForecast: Invalid Date {org.apache.synapse.mediators.bsf.ScriptMessageContext}
TID: [-1234] [] [2017-11-09 11:10:08,918] ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} - The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: RangeError: Date is invalid. (<Unknown Source>#137) in <Unknown Source> at line number 137
at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)
at javax.script.CompiledScript.eval(CompiledScript.java:92)
It seems that this date is invalid and it can't create the Date object.
From what I understood reading online the problem should be that old JS or Rhino (maybe the version of JS implemented by Rhino) does not support date of this type and probably I have to convert it in a date format which is fully compliant with ISO 8601
So I think that I have to convert my string 2017-11-09 06:00:00 into something like compliant with ISO 8601 standard.
I can't use third party library.
How can I do it?
Can use Date#toISOString() or Date#toJSON()
let d = new Date('2017-11-09 06:00:00')
console.log(d.toISOString())
console.log(d.toJSON())
//if you want convert date without convert in timezone than
var date = '2017-11-09 06:00:00';
var convertDate = date.replace(" ", "T"); // 2017-11-09T06:00:00
//if you want to convert in date with utc timezone
var date = new Date("2017-11-09 06:00:00").toISOString()
If I've understood your question correctly the problem is not so much that you need a ISO 8601 formatted date, but it is that you need to create a Date object from a date that is not formatted in ISO 8601. I personally would just use regular expression to parse the date into it's parts and then pass them into the Date constructor:
var currentOriginalForecast = {
"start_date": "2017-11-09 06:00:00"
};
var rxParseDate = /(\d{4})-(\d\d)-(\d\d)\s+(\d\d):(\d\d):(\d\d)/;
var dateParts = currentOriginalForecast.start_date.match(rxParseDate);
var year = dateParts[1],
month = dateParts[2],
day = dateParts[3],
hour = dateParts[4],
minute = dateParts[5],
second = dateParts[6];
var dateCurrentOriginalForecast = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
console.log(dateCurrentOriginalForecast);
Since there is no timezone mentioned in the start_date, I'm assuming it is UTC and converting it using Date.UTC and passing the resulting timestamp from that into the Date constructor. If start_date is in local time you would just remove Date.UTC and pass the parameters directly into the Date constructor. I'll also mention the month - 1; that is because the Date constructor (and Date.UTC) expect a 0-based month.

javascript giving wrong date after conversion from string to date in IE 8

I'm having date from my app in the format eg.
2013-05-01T00:00:00
when i'm converting this to Date
var d = '2013-05-01T00:00:00'
var result = new Date(d);
getting result as NaN
when i do,
var result = new Date(d.replace(/-/g, '/'));
getting result as,
Tue Apr 30 22:30:00 UTC+0530 2013
what could be the reason that i'm getting date 1 day before..
You should always parse date strings yourself, browsers are notoriously bad at it. For examle, some browsers will treat '2013-05-01T00:00:00' as UTC and others as local. It should be treated as UTC (since the timezone is missing), so:
function parseDateString(s) {
s = s.match(/\d+/g);
return new Date(Date.UTC(s[0], --s[1], s[2], s[3], s[4], s[5], (s[6] || 0));
}
which will create a date object using the above values as UTC and with a timezone offset based on current system settings. So if your current timezone is UTC+0530, you should get the equivalent of:
2013-05-01T05:30:00+0530
however you seem to be getting a value for UTC-0130. I have no clue about that.
Oh, when you do:
new Date(d.replace(/-/g, '/'));
you are totally mangling the string so it is not an ISO 8601 string and you are completely at the mercy of an implementation dependent date parser (i.e. every implementation may be different, if that's possible).

Compare different time zone date in Jquery

How to compare dates from different time zone?
for e.g.
x = "2013-12-02T10:10:17-0400" // (timezone EST)
and compare this date to current date
var d = new Date(); // timezone(PST)
check x < d ?
When it comes to dealing with dates and times in JavaScript, I usually use Moment.js which is a library exactly for this purpose.
Its URL is http://momentjs.com/
Then you can simply parse the given string with this line:
// Parse the given datetime
var mydate = moment("2013-12-02T10:10:17-0400");
And you can also compare two different moment values:
// Compare given datetime with the current datetime
if (moment("2013-12-02T10:10:17-0400") > moment()) {
// ...
}
Or you can just convert it to a regular JavaScript Date object:
// Parse given datetime and convert to Date object
var mydate = moment("2013-12-02T10:10:17-0400").toDate();
// Compare to current datetime
if (mydate > (new Date())) {
// ...
}
Note that the unary + operator also works with moment objects just as you would expect. So +moment() outputs the same as +(new Date()).
It's also very well documented, the Moment.js docs page has a ton of examples and useful info about it.
Better convert any of the dates to a common timezone(better to have UTC)
Now convert the datetime to milliseconds
Compare the milliseconds
Hope you understand
Use this javascript library to manipulate dates in different time zones: https://github.com/mde/timezone-js
It uses the TZ database: http://en.wikipedia.org/wiki/Tz_database

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories