Wednesday, 12 December 2012

Datepicker date format helper

I have been working on dates and multi language implementation.
I have wrote small class that helps with dates and jQuery.




 
using System.Globalization;
 
namespace HtmlHelpers
{
    public class DateTimeTimeHelper
    {
        /// <summary>
        /// Override jquery date time format with format from current thread.
        /// </summary>
        /// <returns>Javascript format to override jquery date picker settings.</returns>
        public static string OverrideFormat()
        {
            string str = "<script type=\"text/javascript\">";
            str += string.Format("$.datepicker.setDefaults({ dateFormat: '{0}' })"DateTimeTimeHelper.GetDateFormatPatternForCulture());
            str += "</script>";
            str += "</head>";
            return str;
        }
 
        /// <summary>
        /// Get date format pattern for UI culture.
        /// </summary>
        /// <returns>String pattern.</returns>
        public static string GetDateFormatPatternForCulture()
        {
            var dateFormat = GetJavascriptShortDatePattern(System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat);
 
            return dateFormat;
        }
 
        /// <summary>
        /// Gets the javascript short date pattern.
        /// </summary>
        /// <param name="dateTimeFormat">The date time format.</param>
        /// <returns>Reformated short date string.</returns>
        public static string GetJavascriptShortDatePattern(DateTimeFormatInfo dateTimeFormat)
        {
            return dateTimeFormat.ShortDatePattern.Replace("M""m").Replace("yy""y");
        }
 
        /// <summary>
        /// Gets the javascript short date pattern.
        /// </summary>
        /// <param name="dateTimeFormat">The date time format.</param>
        /// <returns>Reformated short date string.</returns>
        public string GetJavascriptShortDatePattern(string dateTimeFormat)
        {
            return dateTimeFormat.Replace("M""m").Replace("yy""y");
        }
    }
}