Generate an easy-to-read timestamp from the date. Returns the date as a string in the format: MON 01012008 @ 3:15:55PM - CSharp System

CSharp examples for System:DateTime Timestamp

Description

Generate an easy-to-read timestamp from the date. Returns the date as a string in the format: MON 01012008 @ 3:15:55PM

Demo Code


using System.Collections;
using System;/*from ww w.java 2s  .  c om*/

public class Main{
        /// <summary>
        /// Generate an easy-to-read timestamp from the date.
        /// 
        /// Returns the date as a string in the format: MON 01/01/2008 @  3:15:55PM
        /// </summary>
        /// <param name="date">The date for which the stamp is generated</param>
        /// <returns></returns>
        public static string PrintLegibleDateWithMilliseconds(DateTime date) {
            string dd = date.Day.ToString();
            string mm = (date.Month).ToString();
            string yy = date.Year.ToString();

            int h = date.Hour;
            if (h > 12)
                h -= 12;
            string hour = h.ToString();
            string min = date.Minute.ToString();
            string sec = date.Second.ToString();
            string ms = date.Millisecond.ToString();

            if (dd.Length == 1)
                dd = "0" + dd;
            if (mm.Length == 1)
                mm = "0" + mm;

            bool pad = (hour.Length == 1) ? true : false;

            if (hour.Length == 1)
                hour = "0" + hour;
            if (min.Length == 1)
                min = "0" + min;
            if (sec.Length == 1)
                sec = "0" + sec;
            if (ms.Length == 1)
                ms = " " + ms;
            else if (ms.Length > 2)
                ms = ms.Substring(0, 2);

            string day = date.DayOfWeek.ToString().ToUpper().Substring(0, 3);
            string period = (date.Hour < 12) ? "AM" : "PM";

            string result = day + " " + mm + "/" + dd + "/" + yy + " @ " + hour + ":" + min + ":" + sec + ms + period;

            if (pad)
                result += " ";
            return result;
        }
}

Related Tutorials