Get Date Key - CSharp System

CSharp examples for System:DateTime Calculate

Description

Get Date Key

Demo Code


using System.Collections;
using System;/*w  ww.  ja va2  s  .com*/

public class Main{
        #endregion

        #region -------- PUBLIC - GetDateKey --------
        public static string GetDateKey(DateTime date) {
            string key = Dates.PrintLegibleDate(date);
            key = key.Substring(0, key.IndexOf("@"));
            key = key.Trim().Replace(" ", "_");
            key = key.Replace("/", "-");
            return key;
        }
        #endregion

        #region -------- PUBLIC - PrintLegibleDate --------
        /// <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 PrintLegibleDate(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();

            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 = " " + hour;
            if (hour.Length == 1)
                hour = "0" + hour;
            if (min.Length == 1)
                min = "0" + min;
            if (sec.Length == 1)
                sec = "0" + sec;

            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 + " " + period;

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

Related Tutorials