I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I
need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.
var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));
Which is the solution?
I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().
You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').
d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.
I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:
function toDate(str){
var months={
"JAN":1,
"FEB":2,
//... other months
"JUN":6,
//... other months
"DEC":12
}
var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
if(r.test(str)===false){
throw new Error("Invalid date string:"+str);
}
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2].toUpperCase()];
if(typeof m==="undefined"){
throw new Error("Invalid month name:"+arguments[2]);
}
var days=arguments[1]
m=(m<9)?"0"+m:m;
days=(days.length===1)?days="0"+days:days;
years=(years>50)?years="19"+years:"20"+years;
return m+"/"+days+"/"+years;
};
return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));
Related
Is there any way to convert any date string (not necessarily current date) (could be any format) to specific date format in Javascript. Like converting "MM-DD-YYYY" or "ddMMYYYY" to "DD-MMM-YYYY"?
I know that from current date as var date = new Date(), we can get time and hours but what to do in case of existing date string like "31/01/1999" to "31-JAN-1999".
Given the input date string can be of any format.
This is a common problem.
You should be able to do it with moment.js.
Ex.
moment("31/01/1999").formatWithJDF("dd - MM - yyyy");
Have a look here, https://momentjs.com/docs/ for more details.
Using DateFormatter.js
var date = new Date('2020-03-25 10:30:25');
var formatter = new DateFormatter();
displayFormat = 'D M d Y h:i:s';
var dateString = formatter.formatDate(date, displayFormat); // Wed Mar 25 2020 10:30:25
This can be done by first checking the input date format with the arrays or Map of regex provided, then need to convert that format to JS accepted format ISO format.
Once converted to ISO format this date now can be converted to any form with logic written for it in separate functions.
I have given a very unusual date format in string. I need to convert it to a JS date object and add up a few days. The last step is clear, but I don't know how to convert the string into the JS date object. Take a look at the string date: October 02, 2016
You should use moment.js
Syntax:
moment(dateString, format, locale)
var dateStr = "Oktober 02, 2016"
var d = moment(dateStr, "MMM DD, YYYY", 'de');
console.log(d.format("DD-MM-YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment-with-locales.min.js"></script>
Use Date.parse() to parse the date and get the Date object.
var dateObj = new Date('October 02, 2016')
Now, you can perform all the Date operations on dateObj
Given that everything is static here, I thing the best case for you might be to keep a map of your month's name against there number i.e say Oktober : 8. This way you will easily get around of any locale issue in any library.
Once above map is done, you can use .substring to separate your string for blank space and commas to get date and year easily.
Once you have all this you can use new Date constructor with months date and year field.
Hope this all is easily understood, so I am skipping any code here.
Using new Date() can be converted from string to date.
And using setDate() you can add days in the date and can convert the date back to string,
Please check below snippet for more understanding.
var someDate = new Date('October 02, 2016');
console.log(someDate);
console.log(new Date(someDate.setDate(someDate.getDate() + 5)).toString());
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'));
I have a date in a following format:
12/11/2015 07:12 PM
In jQuery I'm doing:
var parsedDate2 = new Date(date);
alert(parsedDate2);
And that prints me:
Fri Dec 11 2015 07:12:00 GMT+0100 (Central European Standard Time)
and that almost works correctly, mostly because in my example (12/11/2015 07:12 PM) the format is DD/MM and not MM/DD. However, jQuery treats it as the month is first. That's a problem, because when I chose as input:
19/11/2015 07:17 PM <--- (19th of November)
I'm getting:
Invalid date
So how can I set up the correct format here with the day before the month?
Ugly, but it work, with JS only :
a = "12/11/2015 07:12 PM";
b = a.split(' ');
c = b[0].split('/');
bad = new Date(a);
alert('bad : '+bad);
good = new Date(c[1]+'/'+c[0]+'/'+c[2]+' '+b[1]+' '+b[2]);
alert('good : '+good);
The other way is to use Moment.js parsing tool
Think that you should use more specialized and focused library along with JQuery, for me the best one is Moment.js - it has all and more than needed to date-time parsing and formatting and doesn't do something else.
Also, there are some other alternatives, like date.js and globalize.js
It's in the form of mm/dd/yyyy. Try 11/19/2015 07:17 PM. Sadly, jQuery doesn't know which format you're using and so, uses the deafult one.
Unfortunately, the Javascript Date system isn't very malleable when it comes to adding date formats. Here is a reference from Mozilla. I think wierdpanda has the right idea, write a function that accepts your date format, reformats it before feeding it to new Date(), and returns the result. Use this in place of where you have new Date(), and all should be good.
I'm working with javascript Date and i'm starting to go crazy :)
I want two compare only the year,month, day of two dates. The date are (retrieve from firebug stacktrace):
[Date {Thu Feb 11 2010 12:00:00 GMT+0000 (GMT Standard Time)}]
[Date {Sun Jul 11 2010 00:00:00 GMT+0100 (GMT Daylight Time)}]
In this point i'm trying compare the two dates like this:
if (datepickerBegin == null || datepickerBegin.length == 0 || datepickerBegin != date) {
//Do stuff
}
This code obvious doesn't work, which is the simple way of comparing these two String?
I'm trying to convert this var to Date and concatenate into another var the getMonth()+getYear()+getDay()... but
i believe that there is a easiest way.
By the way, why the following line give NaN
new Date(datepickerBegin).getMonth()
but the following line works?
new Date(Date.parse(datepickerBegin.toString())).getMonth()
After parsing the dates using Date.parse(...);, you can use the Date constructor to create date types like so. An example of this process has been abstracted into the function below:
function parseDateAsDatePart(dateString) {
var parsedDate = new Date(Date.parse(dateString));
return new Date(parsedDate.getYear(), parsedDate.getMonth(), parsedDate.getDate());
}
Once you change both strings into Date objects, you may compare them as shown above.
Note: as Linus mentioned above, Date.parse(...) returns an integer, not a date object, so it needs to be wrapped in the Date constructor.
Try converting the dates to time, using the .getTime() method. If the dates are equal, they will have the same values returned from getTime. This assumes that you're only using string values for your dates (ie "9/6/12"). If your dates will have time stamps associated with them, then you'll need to use the setHours() function to set all the time reference to 0 (d.setHours(0,0,0,0);).
Links:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTime
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setHours
Example:
if(datePickerBegin.getTime() === datePickerEnd.getTime())
{
//...do something.
}
Note: If you do end up going the .getMonth() route, then be aware that the function returns the months as zero based numbers, so add 1 to what it returns.
You can try with getMonth, GetDays , ...
http://www.comptechdoc.org/independent/web/cgi/javamanual/javadate.html