The example below shows the different ways, to format datetime into a string in C#
using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s;
DateTime dt = System.DateTime.Now;
Console.WriteLine(dt);//Displays 5/8/2011 8:50:40 AM
s = dt.ToString("d");
Console.WriteLine(s);//Displays 5/8/2011
s = dt.ToString("MM-dd-yyyy");
Console.WriteLine(s);//Displays 05-08-2011
s = dt.ToString("MM/dd/yy"); //month date year
Console.WriteLine(s);//Displays 05/08/11
s = dt.ToString("MM-dd-yy");
Console.WriteLine(s);//Displays 05-08-11
s = dt.ToString("dd/MM/yy");//date moth year
Console.WriteLine(s);//Displays 08/05/11
s = dt.ToString("dd-MM-yy");
Console.WriteLine(s);//Displays 08-05-11
s = dt.ToString("dd");
Console.WriteLine(s);//Displays 08
s = dt.ToString("MM");
Console.WriteLine(s);//Displays 05
s = dt.ToString("yy");
Console.WriteLine(s);//Displays 11
s = dt.ToString("yyyy");
Console.WriteLine(s);//Displays 2011
s = dt.ToString("m");
Console.WriteLine(s);//Displays May 08
s = dt.ToString("y");
Console.WriteLine(s);//Displays May, 2011
//Do this to get the month name
char comma = ',';
s = dt.ToString("y").Split(comma)[0];
Console.WriteLine(s);//Displays May
//Do this to get the day name
s = dt.ToString("dddd");
Console.WriteLine(s);//Displays Sunday
s = dt.ToString("mm");
Console.WriteLine(s);//Displays 50 (minutes)
s = dt.ToString("ss");
Console.WriteLine(s);//Displays 40 (seconds)
}
}
}
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator