javascript time formatting/interpreting function? - javascript

I am working on a web-based application that will require users to enter a start and end time
I find selection boxes annoying for that purpose, and I am looking for any javascript functions that will interpret most entries that a user could put
for example:
1p, 1pm, 1:00pm, 13, 13:00 would all be 1:00PM
I know I can write it, but if someone has already written a comprehensive one, it would be appreciated.
Thanks,

Checkout Date.JS. The sample parser on their website correctly parses all the formats you have listed except 13, which it considers to be the date and parses as Dec 13 instead of 1PM.

Related

angularjs $valid on dates reports incorrectly in firefox

I have noticed an issue with form validation on dates within firefox, that I would greatly appreciate any advice or a usable work-around for.
Date Validation Problem
I am using angularjs v1.3.11, and the issue i'm experiencing is actually with the bootstrap datepicker, however it is the same issue for a standard input type="date" field.
If I put an invalid leap day e.g. 29/02/2013 (en-GB date - DD/MM/YYYY) into a text field using bootstrap datepicker or an input type="date" field $valid on that form field reports as invalid on ALL browser accept for firefox. I really want it to report as invalid on every browser!
It appears to invalidate a date, if I for example put complete garbage into the field such as entering a date without a month so 29/2013 would quite rightly report as invalid in all browsers I've tested. It's almost as if angular is running a special regex for firefox that doesn't care about the validity of a date other than that it has 3 sets of numbers in it.
Viewing this date issue on the angular website
If you select the following link https://code.angularjs.org/1.3.11/docs/api/ng/input/input%5Bdate%5D you will be taken to angulars own write up of input[date].
Follow the link in firefox - scrolling to the bottom of the page to the example they've put on the screen and type in an invalid date such as 29th February 2013 (It seems to need ISO date format for firefox on this site) and you will see it report the date youv'e entered as valid, even though there is no 29th February in 2013 as it was not a leap year.
If you perform the same test in chrome for example, then you will see it report the date as INVALID - which is what I wish to happen.
How to resolve this?
Thankyou if you've managed to read this far! I realise that this may be an issue with how a particular browser deals with dates, although i've searched far and wide and haven't found any listed bugs for this in either firefox or angular.
What i'm really hoping here, is that someone may know a work-around, for example a way of intercepting the call that determines $valid on an input field, so that I can run my own regex or something like that. If anyone know's why this is so strange in firefox i'd love to know that too!
Thanks in advance for any help anyone can offer :)
Lindsay
You need more sophisticated date logic to determine if a date is valid. I suggest using a third party library like moment.js or date.js to perform the date validation logic.
Try the demo link at the bottom of the accepted answer for the following SO question:
Simple angularjs date input
Enter 2013-02-29, it will correctly identify the date is invalid.
Tested on Firefox, IE, and Chrome.

Parsing String Time Format (NOT Time Zones)

Assuming that time formats (not timezone data, just plain-text Strings representing time in 12-hour clock), what is the best way to parse that data (examples below)?
I feel like this is a pretty simple question, but I've though about it a lot and can't figure out a fool-proof process for parsing out hour and minute values from any one of many time "formats".
I'm using a simple form that allows for entering a time (e.g., the time of a reservation), but there is no way to make the form field (Google Forms, limited customizability) anything other than plain-text which allows for any time format a person wishes to put in there a viable piece of data to work with. Here are some examples of times that can be entered:
1 P // hours would be 13, minutes would be 0
3:15 P.M. // hours would be 15, minutes would be 15
4 P.M // hours would be 16, minutes would be 0
8:30 a // hours would be 8, minutes would be 30
10:45 aM. // hours would be 10, minutes would be 45
12:00 Pm // hours would be 12, minutes would be 0
Those are just some examples. Feel free to fix tags if I'm not in the right topic(s) - I am however using Google Apps Script/Javascript to accomplish this.
I thought about building a couple regex strings to look for certain formats (which I'm sure will take me a while to write since I've never written one before).
I also thought about looking for a ':' character, and an 'a'/'A' character or 'p'/'P' for determing whether or not the +12 hours needs to be added. After that kind of information is retrieved the problem could be solved by truncating the 'p.m.'-type sections, then split(":") to get the correct numbers.
I feel like the first approach is much more stable, but the second solution might be easier. I'm not sure if there is a better way though, those are the two methods my n00b programmer mind could come up with.
I'm glad to hear you have an answer that you think will help you out. But before you write too much code, revisit this assertion you made:
...there is no way to make the form field (Google Forms, limited customizability) anything other than plain-text
Here's how you define a question to present a Date & Time picker, using the Forms UI.
The spreadsheet that is receiving your form responses will end up with a Date object - no need to mess around with strings at all.

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.

how to convert Hijari date into Gregorian date in javascript?

I am using intalio editor in that I want to convert the Hijri date into a Gregorian date or vice-versa. we write code in javascript using jsx3 so please help me.
For Gregorian->Hijiri, see here
Bidirectional C# version here that could be converted to Javascript
EDIT: An excellent page and convertors can be found here. That page says:
All calculations are done in
JavaScript executed in your own
browser; complete source code is
embedded in or linked to this page,
and you're free to download these
files to your own computer and use
them even when not connected to the
Internet.
which suggests to me you can use the code, but you probably want to check with the page author
It helps to know that muslims refer to the Gregorian calendar as Masihi. Googling for "hijrah to masihi converter" turns up this page as the second hit: http://www.islamicity.com/PrayerTimes/defaultHijriConv.asp
The javascript is code contains two functions GregToIsl and IslToGreg that does what you want.
There is a copyright notice on that page so you shouldn't simply copy-paste the code. But the functions are short enough for you to extract the relevant maths out of.
The maths/algorithm itself is almost a thousand years old so it shouldn't have any legal restriction.
Try dojox.date.islamic
In Javascript the correct way for such conversion is to use Intl object (read more) as following:
a = new Date();
localeFormat= 'ar-SA-islamic-umalqura';
Intl.DateTimeFormat(localeFormat).format(a)

Localize dates on a browser?

Let's say I have a date that I can represent in a culture-invariant format (ISO 8601).
I'll pick July 6, 2009, 3:54 pm UTC time in Paris, a.k.a. 5:54 pm local time in Paris observing daylight savings.
2009-07-06T15:54:12.000+02:00
OK... is there any hidden gem of markup that will tell the browser to convert that string into a localized version of it?
The closest solution is using Javascript's Date.prototype.toLocaleString(). It certainly does a good job, but it can be slow to iterate over a lot of dates, and it relies on Javascript.
Is there any HTML, CSS, XSLT, or otherwise semantic markup that a browser will recognize and automatically render the correct localized string?
Edit:
The method I am currently using is replacing the text of an HTML element with a localized string:
Starting with:
<span class="date">2009/07/06 15:54:12 GMT</span>
Using Javascript (with jQuery):
var dates = $("span.date", context);
// use for loop instead of .each() for speed
for(var i=0,len=dates.length; i < len; i++) {
// parse the date
var d = new Date(dates.eq(i).text());
// set the text to the localized string
dates.eq(i).text(d.toLocaleString());
}
From a practical point of view, it makes the text "flash" to the new value when the Javascript runs, and I don't like it.
From a principles point of view, I don't get why we need to do this - the browser should be able to localize standard things like currency, dates, numbers, as long as we mark it up as such.
A follow up question: Why do browsers/the Web not have such a simple feature - take a standard data item, and format it according to the client's settings?
I use toLocaleString() on my site, and I've never had a problem with the speed of it. How are you getting the server date into the Date object? Parsing?
I add a comment node right before I display the date as the server sees it. Inside the comment node is the date/time of that post as the number of milliseconds since epoch. In Rails, for example:
<!--<%= post.created_at.to_i * 1000 %>-->
If they have JS enabled, I use jQuery to grab those nodes, get the value of the comment, then:
var date = new Date();
date.setTime(msFromEpoch);
// output date.toLocaleString()
If they don't have JS enabled, they can feel free to do the conversion in their head.
If you're trying to parse the ISO time, that may be the cause of your slowness. Also, how many dates are we talking?
Unfortunately, there is not.
HTML & CSS are strictly used for presentation, as such, there is no "smarts" built in to change the way things are displayed.
Your best bet would be to use a server side language (like .NET, Python, etc.) to emit the dates into the HTML in the format you want them shown to your user.
It is not possible to do this with HTML, it has no smart tags that can make any kind of decisions like this. It is strictly presentational. I do wonder, though, if HTML5 perhaps has a tag for something like this...
Anyways, the way I see it, you have 3 options:
Stick to the Javascript way. There's questions with more details on it on this website, such as How do I display a date/time in the user’s locale format and time offset? and How can I determine a web user’s time zone?
Try to use geolocation. That is, your server side script fires off a request to one of the many geolocator services out there on the user's first page visit to try and guess where the user is. The downside of this is that it will be wrong about 10% of the time, so it's not that much better than the market share Javascript is going to get you.... (all in all, then, not a very good method...)
Ask the user! You will see that most websites that want to display a tailored experience for you will ask you this sort of thing because it's just not possible to know. As a neat fallback, you could wrap the question around <noscript> tags so you only ask those with Javascript disabled while offering the Javascript experience to those that have it.
Dojo has some pretty good localizations for dates and currencies. Using this method also allows you to pick different formats (e.g.: short date vs long date) and force locales.
The language and the user's locale should be sent on the HTTP header. You can use those to create the correct date format server-side to be displayed to the user. However, this is often undesirable because many users completely ignore their locale settings in their OS and/or browser. So, you may be feeding USA style timestamps to New Zealanders.
I liked the trick posted in the comment above, but it sounds like a QA headache, since you could be dealing with a large number of clients that implement timestamps in very different ways.
The most effective solution I have seen, is to simple provide a panel to allow your users to choose what time format they like. Some users even ****gasp**** like ISO formats. Then you do the time format conversion server side. If your application language does not have good locale to timezone formatting mapping, check your database. Many databases provide locale-based customized timezone formatting as well.
Because this anwser still popups in google I share that this is now possible to do by using a readonly datetime-local input (see below) and you can then style the input the way you want:
<input type="datetime-local" value="2018-06-12T19:30" readonly />
For more information see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

Categories

Resources