Get AM/PM for a date time in lowercase using only a datetime format

前端 未结 5 1831
野趣味
野趣味 2020-12-30 18:36

I\'m to get a custom DateTime format including the AM/PM designator, but I want the \"AM\" or \"PM\" to be lowercase without making the rest of of the characters lo

5条回答
  •  佛祖请我去吃肉
    2020-12-30 18:56

    The problem with the above approaches is that the main reason you use a format string is to enable localization, and the approaches given so far would break for any country or culture that does not wish to include a final am or pm. So what I've done is written out an extension method that understands an additional format sequence 'TT' which signifies a lowercase am/pm. The below code is debugged for my cases, but may not yet be perfect:

        /// 
        /// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format.  The format has extensions over C#s ordinary format string
        /// 
        /// this DateTime object
        /// A DateTime format string, with special new abilities, such as TT being a lowercase version of 'tt'
        /// A string representation of value of the current System.DateTime object as specified by format.
        public static string ToStringEx(this DateTime dt, string formatex)
        {
            string ret;
            if (!String.IsNullOrEmpty(formatex))
            {
                ret = "";
                string[] formatParts = formatex.Split(new[] { "TT" }, StringSplitOptions.None);
                for (int i = 0; i < formatParts.Length; i++)
                {
                    if (i > 0)
                    {
                        //since 'TT' is being used as the seperator sequence, insert lowercase AM or PM as appropriate
                        ret += dt.ToString("tt").ToLower();
                    }
                    string formatPart = formatParts[i];
                    if (!String.IsNullOrEmpty(formatPart))
                    {
                        ret += dt.ToString(formatPart);
                    }
                }
            }
            else
            {
                ret = dt.ToString(formatex);
            }
            return ret;
        }
    

提交回复
热议问题