April 22, 2009

csharp(c#) customizing Date time format using toString, for display gridview and database storage

Problem 1: how to display date time in 24 hour format
solution : DateTime.Now.ToString("dd/MM/yyyy HH-mm-ss");
Note:Captial HH is used for 24 hour format.
small for 12 hour format


Problem 2: how to display am/pm in date time or 12 hour format time.

Solution : DateTime.Now.ToString
("hh-mm-ss tt");
Key: "tt" for AM or PM

Problem 3: how to display time zone in date time.
Solution : DateTime.Now.ToString("hh-mm-ss tt zzz");
Note: zzz is used to display time zone.

Problem 4: how to show full month name in date.
Solution: DateTime.Now.ToString
("dd-MMMM-yy");

Problem 5: how to format full day name in date.

Solution : DateTime.Now.ToString
("dddd-MMMM-yy");
note: MMMM

Problem 6: how to format full year name in date.
Solution: DateTime.Now.ToString
("dddd-MMMM-yyyy");
note: yyyy

Problem 7: how to reduce/subtract date or days

solution : DateTime.Now.AddDays(-10)

for converting date retrieved from database, firstly convert the column to dateTime and use above techniques.

for details of the above solution, you can read followings.....

In C# DateTime class is used to represent the date & time. But for the display purpose on the front end either on

1 data Grid View (GridView / DataGrid) (as by default time field is shown or you want to show in particular format)
2. labels,
3 storing in the database

in to a particular format
for all the above scenario we need to change the date & time format.
as some need only examples and others full details, i will firstly give examples.

GridView

In Grid view we have two ways to show colums

1. Bound Column
2. Template fields
in both we show date format differently.
Bound Field:

<:BoundField DataField="BirthDate" DataFormatString="{0:d}" HeaderText="BirthDate" SortExpression="BirthDate" >
<HeaderStyle BackColor="Green" Font-Names="Verdana" />
</asp:BoundField>>
here DataFormatString="{0:d}" is used to format the date.
"d:" is standard format already defined in c# library,( For details standard format read full article)
or
DataFormatString="{0:dd/MM/yyyy}"

here all specifier are case sensitive.
Template fields:
as we know template fields can be bind using
Eval and Bind functions.
Difference: The Eval function is used to define one-way (read-only) binding. The Bind function is used for two-way (updatable) binding.

to format a date with any of the above method following syntax is used.
'<asp :Label ID="lblDate" runat="server"
Text=
'<%# Eval("CreationDate", "{0:dd-MM-yyyy}") %>'>
</asp>

<asp :Label ID="lblDate1" runat="server"
Text='<%# Bind("CreationDate", "{0:dd-MM-yyyy}") %>'>
'</asp>
-----------------------------------------------------------------------------------------------------------------------
How it works....
DateField..ToString() is used to convert a datetime object to specific format. Internally gridview call this method.

C-sharp comes with two type of format specifier.
  1. Standard
  2. Custom
1. Standard date Format Specifier.
format of these are already defined in the libary.

dt.ToString("y") will show "January, 2009"
Caution now if you want only "9" you will have to prefix a % to interpret it as custom specifier e.g dt.ToString("%d");

other specifiers are.
  • d 1/1/2009
  • D Thursday, January 01,2009
  • t 8:59 PM
  • T 8:59:59 PM
  • f Thursday, January 01,2009 8:59 PM
  • F Thursday, January 01,2009 8:59:59 PM
  • g 1/1/2009 8:59 PM
  • 1/1/2009 8:59:59 PM
Custom format specifiers
if standard specifier are not working for your requirement. use custom format specifier.

when you are using single custom format specifier you need to append either '%' or surround the specifier with spaces e.g ' d ' . else it will collide with the Standard date Format Specifier and you will get wrong/different format.
-----------------------------------------------------------------------
for Day %d dd ddd dddd 01 thu thurday
------------------------------------------------------------------------
for Year %y yy yyyy
Result 9 09 2009
------------------------------------------------------------------------
for Month %M MM MMM MMMM
Result: 1 01 Jan January
------------------------------------------------------------------------
for Hour %h hh H HH
result: 8 08 20 20
------------------------------------------------------------------------
for minute %m mm
Result: 59 59
------------------------------------------------------------------------
for Sec %s ss
result: 59 59
------------------------------------------------------------------------
AM PM : tt
Result: PM
--------------------------------------------------------------------------
Time zone: zzz
Result +05:30
--------------------------------------------------------------------------

for e.g changing form 12 hrs format to 24 hours format or some time you want to show full year name, full month name.

DataBase

Different databases have different format for storing the date. so it needs to be change.
e.g: like sqlserver, oracle, mysql and postgresql store the date in following format yyyy-mm-dd.
oracle- mm/dd/yyyy etc.

for these purposes C# has provided many format strings.
----------------------------------------------------------------------------------------------
Example: 1-jan-2009 08-59-59 PM
how to create a DateTime Object. This date object will be used for all the example below.

DateTime dt = new DateTime(2009,01,01,20,59,59);
//Parameters order wise

year
The year (1 through 9999).
month
The month (1 through 12).
day
The day (1 through the number of days in month).

hour
The hours (0 through 23).
minute
The minutes (0 through 59).
second
The seconds (0 through 59).
  1. Now to format string date as 20-January-2009
    dt.ToString("dd-MMMM-yyyy");
    Caution: for Month capital M is used.
  2. Now to get the short day name of date and short month name
    dt.ToString("ddd-MMM-yyyy"); //Thu-Jan-2009
  3. To display data in AM PM format. //08-59-59 PM
    dt.ToString("hh-mm-ss tt"); . //08-59-59 PM
    Caution: small "m", small h and "tt" for AM or PM
    HH capital H is used to display time in 24 hour format.
------------------------------------------------------------------------------------------------
Culture also play role while formatting the dates.
by default CLR picks running thread's culture. you can also specify the differnt culture while formatting the string. My system has default culture en-US.

6 comments:

Anonymous said...

Thanks this was REALLY helpful.

Anonymous said...

thanks this article is good example for datetime formats especially for am pm with date and time formats it solve my problem with datetime format with am pm

Anonymous said...

Hi,

This is Anilkumar.Thank u very much it is very helpfull to me

Bujji said...

can u post examples on web services,state-management and send some interview tips to me

Anonymous said...

Thank u.it really helped us.......

Anonymous said...

Thank You ..!!!