473,396 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Format time

ken
Mostly so I can find this again when I need it:

function formatTime(t) {
var myTime = t.value;
var badFormat = "Bad format";

// Ensure we have a value
if (myTime == "") {
return(true);
}

var regexSplit = /\s+/;
var regexTime = /:/;
var regexMili = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/; // 00:00 to
23:59
var regexHour = /^(0?[1-9]|1[0-2])$/;
var regexMin = /^[0-5][0-9]$/;
var regexAm = /^[aA]/;
var regexPm = /^[pP]/;

// split value into atoms
var atoms = t.value.split(regexSplit);

// If there is only one atom, are we using military time?
if ( (atoms.length) == 1) {
var timeAtom = atoms[0];
if (! regexMili.test(timeAtom) ) {
t.value = badFormat;
t.focus();
t.select();
return;
}
// Split time into hours, minutes
timeAtoms = timeAtom.split(regexTime);
var hours = parseInt(timeAtoms[0]);
var mins = timeAtoms[1];
var amPm = "am";
if ( hours 11) {
if ( hours 12) {
hours = hours - 12;
}
amPm = "pm";
} else if (hours == "0") {
hours = 12;
}
t.value = hours + ":" + mins + " " + amPm;
return(true);
}
var timeAtom = atoms[0];
var amPmAtom = atoms[1];

// Split time into hours, minutes
timeAtoms = timeAtom.split(regexTime);
var hours = timeAtoms[0];
var mins = timeAtoms[1];

// Check hours
if (! regexHour.test(hours)) {
t.value = badFormat;
t.focus();
t.select();
return;
}

// Check minutes
if (! regexMin.test(mins)) {
t.value = badFormat;
t.focus();
t.select();
return;
}

// Check am
if (regexAm.test(amPmAtom) ) {
var amPm = "am";
} else if (regexPm.test(amPmAtom) ) {
var amPm = "pm";
} else {
t.value = badFormat;
t.focus();
t.select();
return;
}

t.value = hours + ":" + mins + " " + amPm;
return(true);
}

See http://kenandrenee.com/timeReformatJs.html for working example.

Mar 21 '07 #1
1 2185
In comp.lang.javascript message <11**********************@b75g2000hsg.go
oglegroups.com>, Wed, 21 Mar 2007 11:46:04, ke*@kenandrenee.com posted:
>Mostly so I can find this again when I need it:
This is not the place for that. Use your own Web site.
>function formatTime(t) {
Overlong and underdocumented. What there is seems to be written in a
peculiarly ambiguous transatlantic dialect - military time can refer
either to the normal 24-h clock or to the use of letters designating
time zone or offset from Greenwich.

There's no need to validate a time (or date) numerically with RegExps
when new Date() already can do that succinctly. But use a RegExp if it
is also necessary to validate a less liberal character pattern.

>See http://kenandrenee.com/timeReformatJs.html for working example.
Also badly designed. It is most inconvenient that, for test, the same
control is used for input and for output.

The code gives output in FFF. It throws away seconds. It claims to
accept standard time, yet it rejects "11:11:11" which is in accordance
with the applicable ISO (and, IIRC, US FIPS) standard. It rejects
24:00, which is allowed by ISO 8601.

The following code, lightly tested, should take any reasonable exact-
seconds time string and return it in standard form - except that *IF*
locally Date.toString() uses am/pm then the result will be 12-h without
am/pm :

Query - does Date.toString() ever give time
other than as hh:mm:ss on the 24-hour clock?

S = "11:33 " // test
T = new Date("1/1/1 "+S).toString().match(/(\d\d:\d\d:\d\d)/)[1]

If Date.toString() can use the 12-hour clock, replacing the .match()[1]
with .replace(/.*(\d\d:\d\d:\d\d)( ?)\s*([ap]\.?m\.?)?/, "$1$2$3") may
serve.

With that approach, omitting seconds is trivial.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 22 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: renee_ld | last post by:
In a query I used the function datediff to calculate the number of minutes between two time periods on a given day. This function returned the number of minutes as a long integer data type. I...
5
by: Macca | last post by:
Hi, I have a table which has a date/time field. I am storing them as follows :- 01/01/2005 11:25 01/01/2005 19:44 02/01/2005 05:04
15
by: Fritz Switzer | last post by:
I'd like to have a string assigned the value of a DateTime.AddMinutes(amount) so that the string is formatted in "HH:MM" format. For example: DateTime.Now.AddMinutes(30) returns "00:30" ...
7
by: Edward Mitchell | last post by:
I have a number of DateTimePicker controls, some set to dates, some set to a format of Time. The controls are all embedded in dialogs. I created the controls by dragging the DateTime picker from...
13
by: Roy | last post by:
Hi all, I'm creating a project that should always use this date format when displays the dates or create dates. The back end database is a SQL Server and I like to know what is the logical way...
2
by: Pat | last post by:
Here is my problem that I am having with a current project. I went and backed up all my hard drives to DVD's. After backing up the drives, I used a batch file to get all the file names from the...
11
by: shsandeep | last post by:
I used the following query to retrieve the date in dd-mon-yyyy format. db2 => SELECT RTRIM(CHAR(DAY(COVG_TYP_STRT_DT))) || '-' || RTRIM(MONTHNAME(COVG_TYP_STRT_DT)) || '-' ||...
3
by: pamela fluente | last post by:
Hi, I wish to create a string from the current date now() so that it looks like the format used by Excel, for instance: 2006-04-16T19:45:42Z How would I achieve that?
10
by: ARC | last post by:
Hello all, General question for back-end database that has numerous date fields where the database will be used in regions that put the month first, and regions that do not. Should I save a...
18
by: Dirk Hagemann | last post by:
Hello, From a zone-file of a Microsoft Active Directory integrated DNS server I get the date/time of the dynamic update entries in a format, which is as far as I know the hours since january 1st...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.