473,703 Members | 2,308 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting dates

If I had a date in the format "01-Jan-05" it does not sort properly
with my sort routine:

function compareDate(a,b )
{
var date_a = new Date(a);
var date_b = new Date(b);
if (date_a < date_b)
{ return -1; }
else
{
if (date_a > date_b)
{ return 1; }
else
{ return 0; }
}
}

I guess it expects the date in mm/dd/yyyy format.

Do I have to change:

var date_a = new Date(a);
var date_b = new Date(b);

so it recognizes a correct format?

Mike

Jul 28 '05 #1
22 4157
mike wrote:
If I had a date in the format "01-Jan-05" it does not sort properly
with my sort routine:
The arguments for Date() are:

Date( [year[, month[, date[, hours[, minutes[, seconds[, ms]]]]]]])

All arguments are optional.

function compareDate(a,b )
{
var date_a = new Date(a);
Assuming input is as posted and noting that months are numbered from 0
to 11:

var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11 };
var aBits = a.split('-');
var date_a = new Date( a[2], months[a[1].toLowerCase()], a[0] );

and the same for b. Note that you should validate all input first and
that 'date_a' is a valid date for whatever purpose you intend to use it for.

e.g. if '00-Jul-2005' is input, the resulting date will be 30-Jun-2005.
'32-Jul-2005' gives 01-Aug-2005
var date_b = new Date(b);
if (date_a < date_b)
{ return -1; }
else
{
if (date_a > date_b)
{ return 1; }
else
{ return 0; }
}
}

I guess it expects the date in mm/dd/yyyy format.


No, 'it' doesn't. There is a lot more stuff on dates here:

<URL:http://www.merlyn.demo n.co.uk/js-dates.htm>
[...]

--
Rob
Jul 29 '05 #2
Rob thanks i can understand what is goin on there.

works fine.

Jul 29 '05 #3
RobG wrote:
mike wrote:
If I had a date in the format "01-Jan-05" it does not sort properly
with my sort routine:
As a hint, simply reformatting as yyyy-mm-dd will sort correctly (and be
in an ISO acceptable format that is recognised internationally ). There
is no need for using date objects at all (though you may wish to use
them to validate your dates before attempting to sort them).

Below is a simple example, no validation of input or dates is attempted
but would be required in practice.

I have kept the months as zero-indexed - you may wish to change that.
<script type="text/javascript">

var months = { 'jan':0, 'feb':1, 'mar':2, 'apr':3,
'may':4, 'jun':5, 'jul':6, 'aug':7,
'sep':8, 'oct':9, 'nov':10, 'dec':11 };

function sortDates(){
var D = [];
var i = arguments.lengt h;
while ( i-- ) {
D[i] = formatAsYMD( arguments[i] );
}
return D.sort();
}

function formatAsYMD( str ) {
var x = str.split('-');
return x[2] + '-'
+ addZ( months[x[1].toLowerCase()] ) + '-'
+ addZ( x[0] );
}

function addZ( x ) {
return ( x < 10 )? '0' + x : x;
}

</script>

<form action="">
<input name="dStrA" value="28-Jul-2005">
<input name="dStrB" value="28-Aug-2005">
<input name="dStrC" value="2-Feb-2003">
<input type="button" value="show date" onclick="
alert( sortDates(
this.form.dStrA .value,
this.form.dStrB .value,
this.form.dStrC .value
)
);
">

</form>


The arguments for Date() are:

Date( [year[, month[, date[, hours[, minutes[, seconds[, ms]]]]]]])

All arguments are optional.

function compareDate(a,b )
{
var date_a = new Date(a);

Assuming input is as posted and noting that months are numbered from 0
to 11:

var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11 };
var aBits = a.split('-');
var date_a = new Date( a[2], months[a[1].toLowerCase()], a[0] );

and the same for b. Note that you should validate all input first and
that 'date_a' is a valid date for whatever purpose you intend to use it
for.

e.g. if '00-Jul-2005' is input, the resulting date will be 30-Jun-2005.
'32-Jul-2005' gives 01-Aug-2005
var date_b = new Date(b);
if (date_a < date_b)
{ return -1; }
else
{
if (date_a > date_b)
{ return 1; }
else
{ return 0; }
}
}


And that could be:

return ( a < b );

I guess it expects the date in mm/dd/yyyy format.

No, 'it' doesn't. There is a lot more stuff on dates here:

<URL:http://www.merlyn.demo n.co.uk/js-dates.htm>
[...]

--
Rob
Jul 29 '05 #4
Ron,

i am pulling the dates from Oracle and they are in that 27-Jul-05
format. I'd like to change them by using some oracle functions or
coldfusion functions but am unable to (this would be another subject
alltogether) until it gets to the page. The data is loaded to the page
in an array is loaded dynamically. The user has the choice of sorting
the columns, thus the array needs to be sorted and reapplied to the
page.

The page does not know how many fields will be in the array page or
what order they will be. The user selected them on the previous page.

So thanks for your help.I think that will work and I'll going to chek
out this other code as well.

Jul 29 '05 #5
fox


mike wrote:
Ron,

i am pulling the dates from Oracle and they are in that 27-Jul-05
format. I'd like to change them by using some oracle functions or
coldfusion functions but am unable to (this would be another subject
alltogether) until it gets to the page. The data is loaded to the page
in an array is loaded dynamically. The user has the choice of sorting
the columns, thus the array needs to be sorted and reapplied to the
page.

The page does not know how many fields will be in the array page or
what order they will be. The user selected them on the previous page.

So thanks for your help.I think that will work and I'll going to chek
out this other code as well.


// a little conversion shortcut

var mos = { Jan:"01",
Feb:"02",
Mar:"03",
Apr:"04",
May:"05",
Jun:"06",
Jul:"07",
Aug:"08",
Sep:"09",
Oct:"10",
Nov:"11",
Dec:"12"
};

String.prototyp e.oracleDateVal ue = function()
{
return this.replace(/(\d+)-(\w+)-(\d+)/,
function(s, p1, p2, p3)
{
return "20" + p3 + mos[p2] + p1;
});
}
function
oracleDateCompa re(a,b)
{
return a.oracleDateVal ue() - b.oracleDateVal ue();
}
oracleDatesArra y.sort(oracleDa teCompare);
** I have assumed that oracle uses leading zeros where necessary, ex:

01-Jun-00 for June 1, 2000

if not, you can force leading zeros for dates (and months) with:

("0" + p1).replace(/(\d\d)$/,"$1");
anyway, the oracleDateValue should return an integer in YYYYMMDD format
(year 2000 >) which sorts quite easily.
to answer your previous post:

String.prototyp e.oracleDate2Co mmon = function()
{

return this.replace(/(\d+)-(\w+)-(\d+)/,
function(s, p1, p2, p3)
{
return mos[p2].replace(/^0/,"") + "/" +
p1.replace(/^0/,"") + "/20" + p3;
});
}

will convert 25-Aug-05 to 8/5/2005

you can simplify the expression by setting up the mos object without
leading zeros.

Jul 29 '05 #6
fox wrote:


mike wrote:
[...] String.prototyp e.oracleDateVal ue = function()
{
return this.replace(/(\d+)-(\w+)-(\d+)/,
function(s, p1, p2, p3)
{
return "20" + p3 + mos[p2] + p1;
});


Function arguments in String.replace( ) are not supported in some
browsers, e.g. Safari and according to Mike Winter:

"... IE5 and earlier ... don't support function arguments, and
Opera 6 won't perform a replacement at all (a no-op)."

There may be others.

Returned strings should probably contain delimiters (say '-') to make
them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.

[...]
--
Rob
Jul 29 '05 #7
fox


RobG wrote:
fox wrote:


mike wrote:
[...]
String.prototyp e.oracleDateVal ue = function()
{
return this.replace(/(\d+)-(\w+)-(\d+)/,
function(s, p1, p2, p3)
{
return "20" + p3 + mos[p2] + p1;
});

Function arguments in String.replace( ) are not supported in some
browsers, e.g. Safari and according to Mike Winter:

"... IE5 and earlier ... don't support function arguments, and
Opera 6 won't perform a replacement at all (a no-op)."



There may be others.
That is a PISS POOR argument. From whom are you repeating it?
[my take on these other browsers]
Until these browsers get their numbers up... they don't matter -- not to
my clients, and therefore, not to me.

My clients are business people... they want sites for other business
people... they're ALL using PCs with some form of Windows and using IE
as their browser. In the past 2 years, I've talked with exactly 1
"prospectiv e" client that used Firefox (so NOT a problem for me!). It
would seem the only people around here (i.e., in the area where I live)
using "off-brand" browsers are the programmers -- and that "prospectiv e"
client just picked my brain a little, then did the work himself.
So, 100% of my clients use IE5.5+ -- when I ask about Netscape or "other
browser" support -- oddly enough -- THEY don't care (I do a LOT of work
I don't have to do -- but I DO draw a line)... Everybody THEY know uses IE.

Safari has so many other problems with it -- I only use it to read my
daily news... any serious surfing on the Mac and I go to Firefox.

Opera SUCKED so badly early on -- i gave up after the v3 (i think) --
and it's numbers are still so low... they're just one of the arguments
for those who keep saying "you can't do something because..." Besides --
don't you have to pay for opera? It will never be a contender.

[back to topic]
And what exactly is keeping these browsers from supporting this feature?
Even *I* can write the code that handles functions in replace:

String.prototyp e.replace2 = function()
{

if(arguments.le ngth < 2) return null; // or whatever...

var re = arguments[0];
var replacement = arguments[1];

var matches = this.match(re);

if(typeof replacement == "function")
{
return replacement( matches[0],
matches[1],
matches[2],
matches[3],
matches[4],
matches[5],
matches[6],
matches[7],
matches[8],
matches[9]);
}
else
{
return "I'll leave the rest as an exercise!";
// $1..$9 must be accounted for...
// hence, (hint) the matches array from 0 to 9
}
}
and then (even with just this little bit) my little date "turnaround s"
WILL work in Safari [tested] (as well as IE, and Mozilla(s)); [I won't
even install Opera anymore so -- no tellin'... I will assume Konqueror
has similar problems as Safari is based on it]
Finally -- Just because something doesn't work in all browsers, doesn't
mean that with a little effort, it can't be made to work. I'm tired of
all the laziness of those who sit back and criticize or complain that
something cannot be used because some pitiful relatively insignificant
browser doesn't support the feature when worthwhile solutions to
problems can be found. This one was easy (it took considerably longer to
write this response than it did to come up with the solution - about 8
minutes). I don't let a little thing like "minor browser" disfunction
stand in my way. Why do you? Because somebody *else* said so?


Returned strings should probably contain delimiters (say '-') to make
them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.

comparing strings no doubt takes longer than comparing numbers.

if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
they are all in the first week of the same year and month, then the
MINIMUM # of comparisons needed to be made to pass one as <> the other
would be 10 (one per character as long as they are equal) - two week
span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
strings in one "throw" (I used to do it in C -- up to 8 characters at a
time -- typecast to longints -- really good way to speed up searches too)
with integers:
2 numbers, 1 subtraction... you do the math...

[but this only matters if the operations are "time-critical"]

oh... that little YYYYMMDD integer format -- it's called a "packed" date
format (packing integers is a "time-honored programming tradition") --
been around for considerably longer than JavaScript. Technically, the
"digits" should be hexadecimal, but for sorting purposes, decimal digits
work just as well with the extra added benefit of being easily readable
in human terms.
[...]




Jul 29 '05 #8
fox wrote:
[...]
Function arguments in String.replace( ) are not supported in some
browsers, e.g. Safari and according to Mike Winter:

"... IE5 and earlier ... don't support function arguments, and
Opera 6 won't perform a replacement at all (a no-op)."

There may be others.

That is a PISS POOR argument. From whom are you repeating it?


The attribution is right where I posted it. It came from another
thread where you also proposed using functions with the replace
method. It is useful to point out to others where things may fail -
what they choose to do with that advice is completely up to them.
[my take on these other browsers]
Until these browsers get their numbers up... they don't matter -- not to
my clients, and therefore, not to me.
Whatever is posted here is expected to be suitable for the web in
general and not be specific to intranets or corporate clients. If
specific advice has know limitations then they should be noted so that
others may decide for themselves whether it suits their circumstance
or not.

Excluding certain browsers purely on the basis that they are a small
minority is not reasonable.

[...]
Returned strings should probably contain delimiters (say '-') to make
them more obviously dates (yyyy-mm-dd). Sorting should be unaffected.


comparing strings no doubt takes longer than comparing numbers.

if all dates to be sorted are in YYYY-MM-DD format, and -- worst case,
they are all in the first week of the same year and month, then the
MINIMUM # of comparisons needed to be made to pass one as <> the other
would be 10 (one per character as long as they are equal) - two week
span, 9 -- etc... Unless, of course, JavaScript can compare "chunks" of
strings in one "throw" (I used to do it in C -- up to 8 characters at a
time -- typecast to longints -- really good way to speed up searches too)


The idea is to have them in a format that sort() can use without any
further modification and that doesn't require a comparison function.
Whether they are strings or numbers will likely make very little
difference in the OP's case as whatever operations are done to the
table rows will likely take far, far longer than the actual sort.
with integers:
2 numbers, 1 subtraction... you do the math...
Unless you know the actual internal algorithm of how the sort works,
discussing what you think it might be doing means you are basing your
argument on conjecture.

[but this only matters if the operations are "time-critical"]

oh... that little YYYYMMDD integer format -- it's called a "packed" date
format (packing integers is a "time-honored programming tradition") --
been around for considerably longer than JavaScript. Technically, the
"digits" should be hexadecimal, but for sorting purposes, decimal digits
work just as well with the extra added benefit of being easily readable
in human terms.


So you know some other names for that format - bravo. I made no
assertion that it was peculiar to JavaScript - I know it isn't.

I suggested the ISO standard format since it is an international
standard that is unambiguous and widely understood and therefore very
well suited for the web. It also sorts effortlessly and therefore is
likely suitable for this and many other purposes.

The OP may think it's a load of crap and totally ignore everything I
posted - ain't life grand.
--
Rob
Jul 29 '05 #9
As the OP is appreciate the help, but not the bickering much.

My opinion: I really don't have the time to write code for each
browser. It depends on who the user is. I have a neighborhood site
where there are alot of older people and some of them have macs, and
some netscape, but mostly ie. Still i have to write generic code for
them.

I prefer to write for IE, because of the dhtml. I have some pages that
support only ie and i tell the user up front, i.e. they can't login
unless they are using IE. If they dont have IE they can't play.

I really appreciate all the posters help here though, and comments.

Mike

Jul 29 '05 #10

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

Similar topics

6
10894
by: bissatch | last post by:
Hi, I am about to write an application that will display all pdf files in a folder and display them by file name in order of date. Is there an easy way of doing this? I was thinking about somehow adding filename and date created in an array, sorting by date and then printing onto an html page with a link to that file. How would I do this though? Is this the simplest method or is there a better way of doin this?
1
4304
by: John Taylor | last post by:
I have a ListCtrl with 5 columns. The first 4 columns are either strings or integers, but the last column is a string in the format of MM-DD-YYYY. I searched google and also read over the ColumnSorterMixin code & examples, but still can not figure out how to to write a user-defined sort routine just for the last column in order to sort that column by date. I still want the sorting of the first four columns to work as expected. How is...
9
3624
by: p0wer | last post by:
Let's suppose I have this sample document: <root> <entry id="1" <date>2003-08-03</date> <param_1>5</param_1> <param_2>10</param_2> </entry> <entry id="2"> ...
17
3697
by: Matt Kruse | last post by:
I'm looking for the best JS/CSS solution to add functionality to tables. The only browser which needs to be supported is IE5.5+, but no activeX can be used. to be able to do: - Fixed header row - Data sorting (preferrably intelligently determining data type based on content) - If possible, locking the first column from scrolling
18
5744
by: Scott | last post by:
I have a collection where the items in the collection are dates. I want to iterate over the collection and build a value list string for the rowsource of a listbox. The dates in the collection are not in chronological order. Is there a way to first sort the collection and put the dates in chronological order before creating the value list string? Or, how would I iterate over the collection pulling out the dates in chronological order? ...
3
1977
by: melanieab | last post by:
Hi, When you click on a column header to sort in ascending or descending order, numbers (and dates) aren't sorted correctly. It turns up like this: 1 10 11 2 3 4
19
25463
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to sort columns based on the column header the user has clicked in both Ascending and Descending formats.
5
1519
by: Mike | last post by:
I have several datagirds that allow sorting on two date columns. The sorting works but its not showing the newest date first when I sort. For example if I have dates in my column as 01/01/2008 12/01/2007 12/08/2007 02/02/2007
0
8669
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8963
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7872
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4433
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2453
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.