473,385 Members | 1,445 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,385 software developers and data experts.

Formatting dates with ordinal numbers

Hello,

Is there anything in the framework which will format a date to show the
ordinal representation of the day value e.g.

28th June 2007
1st August 2007

instead of

28 June 2007
01 August 2007

I realise that it would be simple enough to write a function for this, but I
wondered if there was anything built-in so as not to reinvent the wheel.

Thanks,

DJ
Jun 28 '07 #1
9 3189
Hi,

"David Jackson" <so*****@somewhere.comwrote in message
news:Ow**************@TK2MSFTNGP02.phx.gbl...
Hello,

Is there anything in the framework which will format a date to show the
ordinal representation of the day value e.g.

28th June 2007
1st August 2007

instead of

28 June 2007
01 August 2007
I dont know for sure, but look into DateTime.ToString() and more
especifically DateTimeFormatInfo provider.
Jun 28 '07 #2
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:%2****************@TK2MSFTNGP04.phx.gbl...

Hi Ignacio,

Thanks for the reply.
I dont know for sure, but look into DateTime.ToString() and more
especifically DateTimeFormatInfo provider.
Those were the first two places I looked but couldn't find anything.

DJ
Jun 28 '07 #3
Hi,

"David Jackson" <so*****@somewhere.comwrote in message
news:ea**************@TK2MSFTNGP04.phx.gbl...
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:%2****************@TK2MSFTNGP04.phx.gbl...

Hi Ignacio,

Thanks for the reply.
>I dont know for sure, but look into DateTime.ToString() and more
especifically DateTimeFormatInfo provider.

Those were the first two places I looked but couldn't find anything.

If not there I doubht you will find it somewhere else :(

Implement it and then share it with the community :)
Jun 28 '07 #4
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:uJ**************@TK2MSFTNGP03.phx.gbl...
Implement it and then share it with the community :)
That seems fair :-)

OK, now this is my first attempt at showing any code in public, so I would
really appreciate any and all criticism. I'm still very much a newbie
compared to most who post in here.

I'm also ashamed to say that I don't really speak any language other than
English, but luckily my French wife helped me with the French formatting. I
guess the main problem here is that this function would need to be extended
to support all of the various cultures in the Framework... Anyway, be
kind...

string EnglishDate = OrdinalDate(DateTime.Now, "MMM", "yyyy", new
CultureInfo("en-GB");
string FrenchDate = OrdinalDate(DateTime.Now, "MMM", "yyyy", new
CultureInfo("fr-FR");

static string OrdinalDate(DateTime DateToFormat, string MonthFormat, string
YearFormat, CultureInfo CI)
{
StringBuilder SB = new StringBuilder();

SB.Append(DateToFormat.Day.ToString("d"));
switch (CI.TwoLetterISOLanguageName)
{
case "en":
{
switch (DateToFormat.Day)
{
case 1:
case 21:
case 31:
{
SB.Append("st");
break;
}
case 2:
case 22:
{
SB.Append("nd");
break;
}
case 3:
case 23:
{
SB.Append("rd");
break;
}
default:
{
SB.Append("th");
break;
}
}
break;
}
case "fr":
{
switch (DateToFormat.Day)
{
case 1:
{
SB.Append("er");
break;
}
default:
{
SB.Append("e");
break;
}
}
break;
}
}
SB.Append(" ");

SB.Append(DateToFormat.ToString(MonthFormat, CI.DateTimeFormat));
SB.Append(" ");
SB.Append(DateToFormat.ToString(YearFormat, CI.DateTimeFormat));

return SB.ToString();
}
Jun 28 '07 #5
On Thu, 28 Jun 2007 14:20:42 -0700, David Jackson <so*****@somewhere.com
wrote:
OK, now this is my first attempt at showing any code in public, so I
would
really appreciate any and all criticism. I'm still very much a newbie
compared to most who post in here.
Because of your desire to make it extensible, I would use the Dictionary<
class to handle the actual look-up (which is mostly what your function
does).

For example (you will note that, counting initialization, this code is
longer than the code you posted, but as new languages are added, two
things are true: 1) this code stays the same length, as code based on your
approach increases proportionally to the data being added, and 2) once
this code is shown to be correct, adding new data is simple and less
error-prone):

(Warning: I haven't compiled any of this code. There may well be some
fundamental syntax errors, like you need to cast something I forgot to
cast. However, I am confident that the basic design is fine, so don't let
any little thing like compiler errors dissuade you. :) )

Dictionary<string, Dictionary<int, string>_dict = new Dictionary<string,
Dictionary<int, string>>();

static string OrdinalDate(DateTime DateToFormat, string MonthFormat, string
YearFormat, CultureInfo CI)
{
StringBuilder SB = new StringBuilder();
Dictionary<int, stringdictLanguage;

SB.Append(DateToFormat.Day.ToString("d"));

try
{
string strPostfix;

dictLanguage = _dict[CI.TwoLetterISOLanguageName].Value;

try
{
strPostfix = dictLanguage[DateToFormat.Day].Value;
}
catch (KeyNotFoundException)
{
// The dictionary must always include key 0, which is the
default
// to use if the actual date number isn't found.
strPostfix = dictLanguage[0].Value;
}

SB.Append(strPostfix);
}
catch (KeyNotFoundException exc)
{
throw new NotSupportedException("Unknown language in CultureInfo
CI", exc);
}

SB.Append(" ");

SB.Append(DateToFormat.ToString(MonthFormat, CI.DateTimeFormat));
SB.Append(" ");
SB.Append(DateToFormat.ToString(YearFormat, CI.DateTimeFormat));

return SB.ToString();
}

The idea being that the _dict field would be initialized to contain
dictionaries for each language you support, each dictionary containing a
default string to append (using index 0) and then specific strings for
specific values. You could of course write explicit code to initialize
the Dictionary<instances, but in keeping with the data-driven model, I
would do something like this:

void InitOrdinalDate()
{
object[] objsDictInit = new object[] {
new object[]
{ "en",
new object[] { "th", 0 },
new object[] { "st", 1, 21, 31 },
new object[] { "nd", 2, 22 },
new object[] { "rd", 3, 23 }
},
new object []
{ "fr",
new object[] { "e", 0 },
new object[] { "er", 1 }
} };

Dictionary<string, Dictionary<int, string>dictLang = new
Dictionary<string, Dictionary<int, string>>();

foreach (object[] arrayLang in objsDictInit)
{
string strLanguage = arrayLang[0];
Dictionary<int, stringdictPostfix = new Dictionary<int,
string>();

for (int i = 1; i < arrayLang.Length; i++)
{
object[] arrayPostfix = arrayLang[i];
string strPostfix = arrayPostfix[0];

for (int j = 1; j < arrayPostfix.Length; j++)
{
dictPostfix.Add(arrayPostfix[j], strPostfix);
}

}

dictLang.Add(strLanguage, dictPostfix);
}

_dict = dictLang;
}

You'd run this code once, and then the OrdinalDate() method would simply
reuse the results each time you call that method. Note also that the
awkward "arrays of arrays of arrays" design can easily be replaced with
something that just reads an XML file or string. IMHO, that would
actually be a better approach than what I posted, but I wanted to get the
illustration out without complicating things further. While I think XML
would be more maintainable, the above has the advantage that is uses only
the basic built-in stuff.

Hope that helps, rather than confuses things further. :)

Pete
Jun 28 '07 #6
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...

Hi Peter,

Thanks for the reply.
Because of your desire to make it extensible, I would use the Dictionary<>
class to handle the actual look-up (which is mostly what your function
does).
OK.
For example (you will note that, counting initialization, this code is
longer than the code you posted, but as new languages are added, two
things are true: 1) this code stays the same length, as code based on your
approach increases proportionally to the data being added, and 2) once
this code is shown to be correct, adding new data is simple and less
error-prone):
Yes, I can see that.
Dictionary<string, Dictionary<int, string>_dict = new Dictionary<string,
Dictionary<int, string>>();
FxCop tells me that it doesn't recommend nested generics - are they really
OK?
Hope that helps, rather than confuses things further. :)
I found it very useful. Thanks again.

DJ
Jun 29 '07 #7
"David Jackson" <so*****@somewhere.comwrote in message
news:uE**************@TK2MSFTNGP02.phx.gbl...
>Dictionary<string, Dictionary<int, string>_dict = new
Dictionary<string, Dictionary<int, string>>();
FxCop tells me that it doesn't recommend nested generics - are they really
OK?
FxCop's recommendations really should taken very much with a pinch of
salt...

Peter's code looks fine to me, and I would have no qualms about using
"nested generics"...

In fact, until I saw your post, the concept of a "nested generic" never
crossed my mind...
--
http://www.markrae.net

Jun 29 '07 #8
On Fri, 29 Jun 2007 04:59:00 -0700, David Jackson <so*****@somewhere.com>
wrote:
[...]
FxCop tells me that it doesn't recommend nested generics - are they
really OK?
I don't know anything about FxCop. Sounds a little fussy to me. :)

I have no idea why it might suggest that nested generics should be
avoided. That's like saying one should avoid putting references to any
class within any other class. But, it should go without saying, since I
wrote the code I at least thought it was okay at the time I wrote it. :)

Pete
Jun 29 '07 #9
Rather than designing and implementing this from scratch, why not look at
one of the Perl or Ruby library functions that already accomplish this, and
convert it to C#?

///ark
Jun 29 '07 #10

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

Similar topics

4
by: Richard Hollenbeck | last post by:
I'm trying to write some code that will convert any of the most popular standard date formats twice in to something like "dd Mmm yyyy" (i.e. 08 Jan 1908) and compare the first with the second and...
12
by: Joseph Numpty | last post by:
Hello everyone. My first post... I'd like to add an automatically updating date field to a webpage. I found the below example on the internet which works brilliantly except I'd like an ordinal...
24
by: PromisedOyster | last post by:
Is there a way that I can get a resultset that contains unique dates in a given date range without the need to have a temporary table and a cursor? perhaps something like: declare @start_date...
11
by: Mark Rae | last post by:
Hi, Does anyone know of a "definitive" source of JavaScript formatting functions e.g. to format numbers, dates, currencies etc? There are loads of examples on the Internet, of course, but I've...
3
by: Steve Weixel | last post by:
I'm having problems getting dates to format the way that I need them to. The problem is that I'm used to the VB6 way of doing things, with which the statement Format(37866, "dd MMM yyyy") would...
4
by: Mark Tarver | last post by:
Prompted by a post on Catalan numbers in Qilang, I got into looking at ordinal numbers as defined by John von Neumann - see http://en.wikipedia.org/wiki/Ordinal_numbers 0 = {} 1 = {0} = {{}} 2...
4
by: yhebib | last post by:
Hello All, I've been browsing and reading all articles I could find on technet ,msdn and other knowledgeable sources to understand the issue I'm dealing with. However, I did not find so far how...
3
by: rugger81 | last post by:
I am currently working in the sql server 2000 environment and I want to write a function to pull all dates within a given date range. I have created several diferent ways to do this but I am...
3
by: myemail.an | last post by:
If I need to format how the content of a field is displayed, I can click ALT + ENTER from design view, and specify the format, for example, the number of decimal digits and so on. Is there a way...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.