Thursday, July 8, 2010

DateTime’s String Formats in C#.net.

DateTime’s String Formats in C#.net.
Hi Friends, This artical shows how to work with the DateTime formats using Sting.Format method.
NOTES:
y :- indicates “year”.
M :- indicates “month”
d :- indicates “day”
h :- hour (12 format)
H :- hour (24 format)
m :- minute
s :- second
Following examples helps you to customize the DateTime format.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DateTimeFormats
{
class Program
{
static void Main(string[] args)
{


//DateTime.DateTime _dt = DateTime.Today.ToLongTimeString();
//suppose today is 08/20/1979 20th august 2010.

Console.Write("Todays Date: ");
Console.WriteLine(DateTime.Today.ToUniversalTime());


Console.Write("year format '10 10 010 2010 (y yy yyy yyyy) ' : ");
Console.WriteLine(String.Format("{0:y yy yyy yyyy}", DateTime.Today));

Console.Write("month format '7 07 Jun June (M MM MMM MMMM) ' : ");
Console.WriteLine(String.Format("{0:M MM MMM MMMM}", DateTime.Today));

Console.Write("day format '29 29 Tue Tuesday (d dd ddd dddd) ' : ");
Console.WriteLine(String.Format("{0:d dd ddd dddd}", DateTime.Today));


Console.Write("hour format(12/24) '4 04 16 16 h hh H HH ' : ");
Console.WriteLine(String.Format("{0:h hh H HH}", DateTime.Today.ToUniversalTime()));

Console.Write("minute format '5 05 m mm' : ");
Console.WriteLine(String.Format("{0:m mm}", DateTime.Today.ToUniversalTime()));

Console.Write("second format '5 05 s ss' : ");
Console.WriteLine(String.Format("{0:s ss}", DateTime.Today.ToUniversalTime()));


Console.Write("second format 'd/M/yyyy HH:mm:ss' : ");
Console.WriteLine(String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Today.ToUniversalTime()));




Console.ReadLine();
}
}
}

OUTPUT is:








As well as if you want to work with Standard DateTime Formatting
Following table shows patterns defined in DateTimeForma¬tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi¬mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta¬bleDateTimePat¬tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent

No comments:

Post a Comment