473,657 Members | 2,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3255
Hi,

"David Jackson" <so*****@somewh ere.comwrote in message
news:Ow******** ******@TK2MSFTN GP02.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.ToStri ng() and more
especifically DateTimeFormatI nfo provider.
Jun 28 '07 #2
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions .comwrote in
message news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..

Hi Ignacio,

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

DJ
Jun 28 '07 #3
Hi,

"David Jackson" <so*****@somewh ere.comwrote in message
news:ea******** ******@TK2MSFTN GP04.phx.gbl...
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions .comwrote in
message news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..

Hi Ignacio,

Thanks for the reply.
>I dont know for sure, but look into DateTime.ToStri ng() and more
especificall y DateTimeFormatI nfo 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******** ******@TK2MSFTN GP03.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(Dat eTime.Now, "MMM", "yyyy", new
CultureInfo("en-GB");
string FrenchDate = OrdinalDate(Dat eTime.Now, "MMM", "yyyy", new
CultureInfo("fr-FR");

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

SB.Append(DateT oFormat.Day.ToS tring("d"));
switch (CI.TwoLetterIS OLanguageName)
{
case "en":
{
switch (DateToFormat.D ay)
{
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.D ay)
{
case 1:
{
SB.Append("er") ;
break;
}
default:
{
SB.Append("e");
break;
}
}
break;
}
}
SB.Append(" ");

SB.Append(DateT oFormat.ToStrin g(MonthFormat, CI.DateTimeForm at));
SB.Append(" ");
SB.Append(DateT oFormat.ToStrin g(YearFormat, CI.DateTimeForm at));

return SB.ToString();
}
Jun 28 '07 #5
On Thu, 28 Jun 2007 14:20:42 -0700, David Jackson <so*****@somewh ere.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<stri ng, Dictionary<int, string>_dict = new Dictionary<stri ng,
Dictionary<int, string>>();

static string OrdinalDate(Dat eTime DateToFormat, string MonthFormat, string
YearFormat, CultureInfo CI)
{
StringBuilder SB = new StringBuilder() ;
Dictionary<int, stringdictLangu age;

SB.Append(DateT oFormat.Day.ToS tring("d"));

try
{
string strPostfix;

dictLanguage = _dict[CI.TwoLetterISO LanguageName].Value;

try
{
strPostfix = dictLanguage[DateToFormat.Da y].Value;
}
catch (KeyNotFoundExc eption)
{
// 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(strPo stfix);
}
catch (KeyNotFoundExc eption exc)
{
throw new NotSupportedExc eption("Unknown language in CultureInfo
CI", exc);
}

SB.Append(" ");

SB.Append(DateT oFormat.ToStrin g(MonthFormat, CI.DateTimeForm at));
SB.Append(" ");
SB.Append(DateT oFormat.ToStrin g(YearFormat, CI.DateTimeForm at));

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<inst ances, 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<stri ng, Dictionary<int, string>dictLang = new
Dictionary<stri ng, Dictionary<int, string>>();

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

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

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

}

dictLang.Add(st rLanguage, 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*********@nn owslpianmk.comw rote 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<stri ng, Dictionary<int, string>_dict = new Dictionary<stri ng,
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*****@somewh ere.comwrote in message
news:uE******** ******@TK2MSFTN GP02.phx.gbl...
>Dictionary<str ing, Dictionary<int, string>_dict = new
Dictionary<str ing, 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*****@somewh ere.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
5364
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 calculate days, months, and years. This is not for a college course. It's for my own personal genealogy website. I'm stumped about the code. I'm working on it but not making much progress. Is there any free code available anywhere? I know it...
12
11756
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 date (e.g. 1st, 2nd, 3rd, 4th) instead of a cardinal date (e.g. 1, 2, 3, 4). How could I do that with this small bit of javascript code? <script language = "JavaScript">
24
4418
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 as datetime declare @end_date as datetime set @start_date as '1/1/2005' set @end_date as '1/1/2006'
11
1566
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 yet to find any which are 100% reliable. Mark
3
4001
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 yield the string "02 Sep 2003". If I run the same thing in dotNet, it gives me back the format string, which isn't very useful. It *does* work If I convert the value to a date beforehand, but unfortunately that doesn't help me because I don't know...
4
5842
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 = {0,1} = {{}, {{}}} 3 = {0,1,2} = {{}, {{}}, {{}, {{}}}} The Qi (see www.lambdassociates.org) definition is
4
4445
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 to fix that. Investigations are still under progress and I hope you'll be able to give hints or feedback that will drive me to the solution. The applications I'm working on until the next release that will soon
3
3026
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 unsatisfied with them. Here is what I have so far: declare @Sdate as datetime declare @Edate as datetime set @SDate = '07/01/2006' set @EDate = '12/31/2006'
3
2106
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 to apply the same kind of formatting to more than one field at the same time? I tried selecting multiple fields, but if then I click ALT + ENTER I don't have the option to choose formatting. Also, how can I format dates as dates? I have a table...
0
8825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
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
8605
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
4151
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
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.