Javascript equivalent to Ruby Time.parse - javascript

I allow users to enter datetime in whatever format they like as long as Ruby's Time.parse method can handle it. Now I need to compare these datetimes in javascript. Is there anything equivalent to Ruby's Time.parse method for javascript?
I need something that can parse for instance "October 13 2012 at 8:15am". I tried datejs but it couldn't handle the "at" word. I would really prefer something that only requires a single function call.

The JavaScript language is picky (and implementations vary) regarding what date format it accepts, so there's no hope without using a library.
Date.js is easily your best bet; however, as you point out, there are sure to be formats that make perfect sense to users but that the library couldn't anticipate.
To workaround, I suggest that you wrap the Date.js parser in a custom scrubbing function that you must maintain:
// using Date.js
function parseDate(str) {
var wordsToRemove = ['on', 'at'] // ...
, regex = new RegExp('\\b(' + wordsToRemove.join('|') + ')\\b', 'g');
return Date.parse(str.replace(regex, ''));
}

Datejs has a really impressive stuff to work with dates in javascript

Try http://momentjs.com/, best time library ever!

This is a bit late, but hopefully it will still help:
If you're only parsing US locale date strings, check out Sherlock.js.
The only limitation is that it doesn't support specifying years or past dates. It can parse 'October 13 2012 at 8:15am' but it will return a Date object for October 13, 2013 at 8:15am, since it always looks forward. You could write some RegEx, like /\b20\d\d\b/ to parse out the year from the string yourself though if needed.
Disclosure: I am the creator of Sherlock.js

Related

Converting JavaScript date to JSON/.net date format

I have a regular date i.e.:
date= 03-12-2014
I need to convert it to JSON or .Net date format. Like this:
"\/Date(1283219926108)\/"
I can see a lot of posts that go from JSON date to regular date but not backward. Please let me know how to do it. I am hoping for some easy JavaScript way to do it.
Do you know/Have you tried (new Date).getTime()
That's the most easiest "cross-browser" solution I know of ...
In your situation something like:
(new Date(date)).getTime()
It's a little bit vague to see what the difference is between .net- and javascript code.
Can you point it out more clearly?
Take a look at this little jQuery file. https://gist.github.com/gigi81/1868478
It does date parsing for .NET.

JSON date, display original date in the server's timezone

For example, I have a string date like this (I'm getting this from the server in json, from rails app)
s = "2013-09-01T00:00:00.000+08:00"
I would like to display it like so
01.09.2013
So I'm using moment.js library for this
moment(s).zone("+08:00").format("DD.MM.YYYY")
>> "01.09.2013"
But I don't know if needed timezone is +08:00. If I skip .zone() call, result would be wrong because my browser is in differnt timezone
moment(s).format("DD.MM.YYYY")
>"31.08.2013"
Even though in my original string I had +08:00 at the end.
So, my question is how can I extract time zone from json date string using pure javascript or moment.js library?
The simplest way I can think of is extracting the last 6 characters manually,
s.slice(s.length - 6, s.length)
> "+08:00"
But maybe there is a better approach for this task?
Just use the parseZone function, like so:
moment.parseZone(s)
Documentation is here.
Alternatively, you can use the older approach, which does the same thing:
moment(s).zone(s)

Date format conversion javascript

Consider if we have a date in the format Sat Jul 28 2012 , is there a general a function to convert it in to any wanted format??
say for example 28-07-2012,
deciding the separators like - or /
Javascript's Date object has lots of different versions of toString and different getters, so it should be pretty easy to get the output you want. Scroll down through this documentation to see some of your options. They have pretty good examples too if you click on them.
In addition, the Date constructor is fairly good at taking in most strings and converting it.
var myDate = new Date("Sat Jul 28 2012");
alert(myDate.toLocaleDateString());
Or use the different getters and string concatenation wrapped in a function to make your own.
You can write a function to do it, i dont think there is a Native method:
function convert(dateObj) {
var format = dateObj.getFullYear()+"-";
format += dateObj.getMonth()+"-";
format += dateObj.getDate();
return format;
}
you can customize it however you want. here is the list of methods for the date object
Javascript only outputs it into the standard format you provided above. You can try using the getDate(), getDay(), getMonth() methods (among others) to extract the necessary data and convert it to your liking.
Please refer to W3Schools' description of the JavaScript Date object.

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example
2011-08-31T06:49:28.931 -0700
which it conveniently tells me when I try to submit something like
2011-08-31T06:49:28.931 -07:00
The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.
So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are
1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?
2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...
3) Extra credit: is the format the server requires some sort of standard?
Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.
Try this code:
var d=new Date(Date.now()); // sets your date to variable d
function repeat(str,count) { // EXTENSION
return new Array(count+1).join(str);
};
function padLeft(str,length,char) { // EXTENSION
return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};
var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
padLeft(String(d.getMonth()),2,"0")+"-"+
padLeft(String(d.getDate()),2,"0")+"T"+
padLeft(String(d.getHours()),2,"0")+":"+
padLeft(String(d.getMinutes()),2,"0")+":"+
padLeft(String(d.getSeconds()),2,"0")+"."+
d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;
str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");
alert(str);
You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.
As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

Regular expression to match Date

I am trying to validate following date format through regExp, but still i didn't get ant working solution-
ex.-
OCT-12-2011
FEB-06-1995
how can i do it using regexp.
Thanks in advance!!
Date JS is the first hit on Google.
Comprehensive, yet simple, stealthy and fast. Datejs has passed all trials and is ready to strike. Datejs doesn’t just parse strings, it slices them cleanly in two.
Sample code from their site:
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
The only downside is that it modifies the prototype of build-in Date object. Although it's considered a discouraged practice I doubt that these particular additions will affect you application. There are still plenty of sites using Prototype without any problems.
EDIT: ragarding parsing Date values via RegExps.
Be very careful especially considering different date.toString() implementation in different browsers. Here's what new Date().toString() gave me:
IE9: "Mon Jul 11 14:50:45 UTC+0300 2011"
FF5: "Mon Jul 11 2011 14:51:08 GMT+0300 (FLE Daylight Time)"
If you get those strings from the server and you feel that adding a library just for dates is an overhead you'll be fine with regular expressions.
Don't try to validate it very strictly using a regex. Check the format, using something like this:
[A-Z]{3}-[0-9]{2}-[0-9]{4}
Then, check each part to see whether that part is valid.
... not sure how strictly you want to do this.
var months = [
'JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'
],
regValidate = RegExp('^(?:' + months.join('|') + ')-[0-3][0-9]-\\d{4}$');
alert(regValidate.test('OCT-12-2011'));
Depending on you requirements, the following could do:
^[A-Z]{3}-\d{2}-\d{4}$
Or more elaborate:
^(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-(0[1-9]|[12]\d|3[01])-[12]\d{3}$
Or anything in between :) (You may even elaborate further on the year part.)
If you want to do it with a single regexp, you could use something like:
/^(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-([012]\d|3[01])-[12]\d{3}$/
This will not match a date before JAN-01-1000 or after DEC-31-2999.
Note: do not forget to check for invalid february dates like FEB-30-2011

Categories

Resources