JavaScript Date Validation RegEx OR JS? - javascript

I'm using a date picker built in to my device and it returns the date in format YYYY/MM/DD
and returns the time in format HH:MM 24 hours.
The overall returned string is YYYY/MM/DDT/HH/MM
T being the separator.
What is the best way to validate this so that it matches the format YYYY/MM/DD/T/HH/MM
Regex ? Does JavaScript have validation for date/time built it even if i have to split at T so i have the date and time in separate variables?
Whats the best way/algorithm to do this aswell preformance wise?
If i split my varible in to array like...
["YYYY/MM/DD","HH:MM"]
Is there a regex or js function that validates this best? Preformance is key.
Thanks

I wouldn't be worried about performance, you're not going to be doing this hundreds of thousands of times in a tight loop, presumably.
A regex is a good way to do it, and will be easy to write; if you create the regex once and reuse it, it should perform well too.
Assuming your example of the format is a typo and you meant YYYY/MM/DDTHH:MM, a modern JavaScript engine should also support using that string as the argument to new Date(...) provided you change the / to - (which you can readily do via String#replace). That's because it fits the pared-down ISO-8601 format defined as part of ES5. But older engines (IE8 and earlier, for instance) may not support it, you'd have to test on the browsers you intend to support. But if it's really YYYY/MM/DDT/HH/MM, ignore this paragraph.

Related

Using Python to parse date/time strings in *exactly* the same way as Javascript?

I have some client-side JavaScript code which reads a string and tries to parse it into a Date() object via new Date(theString), displaying the resulting Date as a UTC string to the user. If it's a string that can't be turned into a Date, of course, it becomes an Invalid Date, in which case instead it displays "Not a date/time."
I also have some server-side Python code which essentially does the same thing: takes the user-submitted maybe-a-date, and stores it as either a UTC string or as "not a date".
The trick is, I need the two pieces of code to always behave exactly the same on every single string. I could certainly just make a tiny Python endpoint that uses the existing Python code to send the appropriate response back to the client instead of using Date() client-side, but for various reasons that's an undesirable solution.
So is there a way to translate strings into dates in Python that's guaranteed to work exactly the same way as new Date(myString) does in JavaScript?
So is there a way to translate strings into dates in Python that's guaranteed to work exactly the same way as new Date(myString) does in JavaScript?
No.
It's impossible, because:
Parsing of strings other than the two formats specified in ECMA-262 is implementation dependent and it is easily demonstrated that different implemetations parse the same string differently (e.g. Why does Date.parse('COVINGTONOFFICE-2') return a real date?)
How various implementations parse unsupported formats is not documented, so you can only determine the rules through observing behaviour of every possible string, including those that look nothing like a date, in every implementation, then knowing which implementation you were trying to imitate

In what format should I store dates where I just need the "YYYY-MM-DD" part [duplicate]

In MongoDB, I only need to make date range queries. But the data set is huge (9 M) and coverting a string to DateTime object (I use Perl script) and then inserting them into MongoDB is very time consuming. If I just store the dates as strings "YYYY-MM-DD", would not the range query gt:"2013-06-01" and lt:"2013-08-31" still give me the same results as if they were of datetime type? Are they the same in this scenario? If so, what would be the advantage of storing as a DateTime object.
Thanks.
If you don't care about time-zone support in your application, then using strings for basic queries in MongoDB should work fine (but if it does matter, you'll want a real Date type).
However, if you later want to do date math or use the Aggregation Framework with your date field, it's necessary that the field is actually a Date type:
http://docs.mongodb.org/manual/reference/aggregation/#date-operators
For example, you could use the $dayOfWeek function on the Date typed field.
You could likely do some simple things like group on year by using $substr (doc) in MongoDB, but the resulting code will not be as clear (nor likely perform as well).
While it's not a huge difference, I'd recommend storing them as Date types if possible generally.
I see in the docs for the Perl driver that developers are warned against using the DateTime due to the fact that it is very slow, so maybe if you use Perl regularly, and the Aggregation Framework isn't a big issue, you'd be better off storing them as either numbers or as strings, and converting them as needed in Perl.
If space is an issue, remove unnecessary characters (such as the -):
20130613 ->
4 bytes for length of string
8 bytes encoded as UTF-8
NULL character
That would be 13 characters. A DateTime value in BSON/MongoDB requires 8 bytes on the other hand (as would the Perl $time function).
(I'd strongly recommend you do a bit of performance testing to find out if the performance impact of using a Date type in MongoDB with Perl will impact your typical workflows.)
The advantage of DateTime is a few bytes less on disk. bson stores DateTime as an integer, but "2013-08-31" is a string, at 20 bytes right there.
ISO-8601 (http://www.w3.org/QA/Tips/iso-date) is meant for being able to sort quickly.
In this case, I would always store as datetime.
edit: How time-consuming are you seeing this string-to-datetime conversion? Are you sure that is your bottleneck? I have a hard time believing the conversion is taking as long as you claim.

Angular app and internationalization and localization

we have an existing silverlight app which runs in browser + on hardware.
we want to rewrite this app using angular js and html5.
one of the key requirements with new system is support of internationalization and localization. and target countries are usa, brazil, italy for now.
Am new to this area and have lot of basic questions.
does existing database needs to be redesigned to support same ? i mean to identify columns (product_name/customer_name etc) that needs to have locale specific data and then store data for each locale and modify sprocs and webapi to accept language parameter and then get content based on that. ?
I believe we need to user nvarchar for such columns.
what will happen to currency and date time columns in db ? say there is quantity column then what should be data type of this column in db ? if current locale is Portuguese then will qty stored in Portuguese number.
what is the best practices for storing and retrieving currency column
based on locale.
what is the best practices for storing and retrieving date column
based on locale.
how to handle string checks, numeric checks in webapi methods ?
how to do comparison and checks in javascript for string,number,datetime
please share link to some good pointers which could help.
so in short right from javascript to .net webapi to database (sql) how should we take care of locale dependent logic and fields
thanks.
A lot of questions, let's see if I can answer those.
If your existing application is properly internationalized, I don't think there is any need to modify the database. Just make sure it is able to handle international characters (NCHAR, NVARCHAR, NTEXT in MS SQL, valid character encodings in others).
As for DB design, it is good to keep things locale-independent as long as you can. For instance it is better to store keys in the database and resolve them at runtime. However, if your data is dynamic (i.e. you have product names and their descriptions that changes often), the only way to go is to have translation table and look the data up using valid locale. It's quite complex in relational world (i.e. joins), but it could be done.
2,3. All the numeric columns should be kept locale-independent and formatted on the UI side. The more problematic would be prices and sales orders - you would need an additional column to store the currency code (i.e. 12.34 | USD). On the UI side you would need to pass the code to the Angular currency filter. The only gotcha here is, Angular does not support easy locale context switching, so you would need to use a hacky library like Angular Dynamic Locale to load the formats for you.
Similar. Keep it locale-independent. DB built-in types should automatically handle that for you and give you nice DateTime/DateTimeOffset (in a .Net world) back. The only gotcha would be the time zone - it may make sense to use DATETIMEOFFSET MS SQL type, as others does not store time zone.
There is an alternative way to store date and times in the database - you may decide to store it as a number of milliseconds since January 1, 1970 UTC - as BIGINT type. Especially if you are going to read this directly to JS, you will be able to easily re-create JS Date object (should you need this for calculations or something) in a valid time zone (it works the other way round as well). All you have to do to format date is to use this number (not date, that is AFAIR) and Angular's date filter with UTC as a parameter.
I don't think I understand what you're asking exactly. I guess the question is about validation of user input, rather than API. Well, beware of using Regular Expressions, because JavaScript doesn't handle Unicode well (at least in this area). You'd need to ask more precise question.
Assuming that you have Number and Date objects (i.e. typeof o == 'number') it is straightforward (as in obj1 === obj2).
As far as strings are concerned... Well, str1 === str2 will give you valid answer if you want to be exact. If you want to sort them, modern web browsers (Chrome 14+, Firefox 29+, IE11+) implement EcmaScript 402 Internationalization API so you can do something like str1.localeCompare(str2, locale), see this article.
The real problem occurs when you want to compare two strings case insensitive and accent insensitive for equality (as oppose for ordering like in case of sorting). Basically, there is no way (and this is true even in "big" programming languages like Java or C#).

Asp-net web api output datetime with the letter T

the data in the DB look like this
2011-09-07 14:43:22.520
But my Web API outputs the data and replace the space with the letter T
2011-09-07T14:43:22.520
I can replace the letter T with a space again in jquery, but can I fix this problem from the Web API (make the web api output the original data?)
I also do not want the miliseconds at the end. How can I get rid of them?
The format of how you see the date in the database is usually irrelevant, because it should be passed into .Net as a DateTime - not as a string. (If you are storing it as a varchar in the database, you have a bigger problem.)
ASP.Net WebAPI is returning the value in format defined by ISO8601 and RFC3339. This is a good thing, as it is a recognized machine-readable format. You probably don't want to change it.
If you really want to change it, you would need to implement a custom JSON.Net JsonConverter, deriving from DateTimeConverterBase. This is discussed here and here.
But instead, you should consider how you are using the actual result in your client application. You mentioned jQuery, so I will assume your consumer is JavaScript. In many browsers, the ISO8601 value that you have is already recognized by the JavaScript Date constructor, so you might be able to just do this:
var dt = new Date("2011-09-07T14:43:22.520");
But this won't work in all browsers. And Date doesn't have a whole lot of flexibility when it comes to formatting. So instead, you might want to consider a library such as moment.js. With that in place, you can do this:
var m = moment("2011-09-07T14:43:22.520");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // output: "2011-09-07 14:43:22"
Please note that the format string here conforms to moment.js, not to .NET. There are differences in case sensitivity. Please refer to the moment.js documentation for details.
One other thing - since the value you provided doesn't have either a Z at the end, nor does it have an offset such as -07:00, then I assume it came from a DateTime whos .Kind value is DateTimeKind.Unspecified. You should be aware that when this gets sent into JavaScript (or anywhere else for that matter), there is no information about what time zone is represented. JavaScript will assume the local time zone of the browser.
If that's not what you had intended, then you need to store UTC values in your database, and make sure they have DateTimeKind.Utc so they get serialized with a Z at the end. JavaScript will normalize this to the browser's time zone, but you will still be talking about the same moment in time.
Alternatively, you could use a DateTimeOffset type - which would serialize with the specific offset. JavaScript will still normalize this to the user's time zone.

Grab dates from a website and put into a calender

This is a long-shot and I'm writing because I have not idea where to start.
I want to write some code that can automatically and on regular basis grab the 5 dates from this website and put them into my iCal calender.
Where should I start and end to do this?
I'm pretty good in RoR and Javascript, but have absolutely no idea what technology I should use to accomplish this.
Hope you can shed some light on my question.
Thanks
Assuming the HTML page is always going to keep the same basic structure, you could use something like nokogiri to locate the nodes containing the dates.
You can then use the Date.strptime or DateTime.strptime methods to convert the date from the particular format, into a Date or DateTime object, as required.
As for then adding the dates to your calendar, it's not something I have had to do, but you might want to check out How to interact with a CalDAV server from Ruby?
Use an XMLHttpRequest object in Javascript to download the page that you need and then use a regular expression to parse out the dates. It seems that the dates all have a fixed format:
<b>Mon Day Hr:Min UTC+4</b>
so it should be easy to write the regular expression for this. I don't know the exact Javascript Regex format but here's the .NET equivalent, it should be easy to tweak this to Javascript - hope this helps:
<b>(?<date>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{2} [0-9]{2}:[0-9]{2}) UTC[+-][0-9]+</b>
This finds all date fields in the page - once you have the date fields, each Regex match will have a sub-group named date that contains the actual date part.
If you go to this page: .NET Regex tester you can test the above expression to see how it returns the dates - just copy & paste your page's source with the dates. As I said, this is for .NET, not for Javascript but the differences are not terribly big.
Use a Ruby script. The Mechanize gem can scrape the dates from the web page. Then the ri_cal gem can add them to your calendar. A pure JavaScript approach like xxbbcc suggested may be possible but it will almost certainly be more involved. If you're already familiar with Ruby, I'd recommend taking advantage of the "magic" and let these gems do the dirty work for you.

Categories

Resources