Home » ASP.Net

Manipulating DateTime with C#

12. April 2010 by jdelpay 0 Comments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        { 
            //The following will display: 4/12/2010 9:53:45 AM
            DateTime myDate = DateTime.Now;
            Console.WriteLine(myDate);
           //-------------------------
           //Wish to show the date only?
            Console.WriteLine(myDate.ToString("d"));//Will output 4/12/2010
            //Wish to Show long Date only?
            Console.WriteLine(myDate.ToString("D"));// Will Output Monday, April 12, 2010
            Console.WriteLine(myDate.ToString("M"));//Will Output April 12
            Console.WriteLine(myDate.ToString("Y"));//Will Output April, 2010
            //-------------------------

            // Displaying a message based on the time of the day
            DateTime bonjour = DateTime.Now;

            if (bonjour.Hour < 12)
            {
                Console.WriteLine( "Good Morning!");//you could also change the language
            }
            else
            {
                Console.WriteLine ("Good Afternoon!");

            }

            // Another approach is to use the DateTime constructor as follow

            DateTime myDate2 = new DateTime(2010, 04, 12);
            Console.WriteLine(myDate2.ToString("M/d/yyyy"));


            Console.ReadKey();
        }
    }
}