을 얻을 AM/PM 날짜를 위해 시간이 소문자만 사용하는 형식으로 날짜/시간
-
20-08-2019 - |
문제
나는 사용자 정의 날짜/시간 형식을 포함하여 AM/PM,그러나 저는"내가"또는"PM"하는 소문자 없 만들기의 나머지의 문자는 소문자입니다.
이것이 가능한 단일 형식을 사용하지 않고 regex?
여기에 나는 지금:
item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt")
예를 들어의 출력을 지금 것 일요일,월 31 일,2009 년 1:34PM
해결책
나는 개인적으로 그것을 두 부분으로 형식화 할 것입니다.
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
item.PostedOn.ToString("tt").ToLower();
또 다른 옵션 (SEC에서 조사 할)은 현재 DateTimeOmatInfo를 잡고 사본을 만들고 AM/PM 지정자를 소문자 버전으로 설정하는 것입니다. 그런 다음 해당 형식 정보를 일반 형식에 사용하십시오. DateTimeFormatInfo를 캐시하고 싶을 것입니다.
편집 : 내 의견에도 불구하고 어쨌든 캐싱 비트를 썼습니다. 아마 그렇지 않을 것입니다 더 빠르게 위의 코드보다 (잠금 및 사전 조회와 관련하여) 호출 코드를 더 간단하게 만듭니다.
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
다음은 다음과 같이 시연 할 수있는 완전한 프로그램입니다.
using System;
using System.Collections.Generic;
using System.Globalization;
public class Test
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
}
private static readonly Dictionary<DateTimeFormatInfo,DateTimeFormatInfo> cache =
new Dictionary<DateTimeFormatInfo,DateTimeFormatInfo>();
private static object cacheLock = new object();
public static DateTimeFormatInfo GetLowerCaseInfo()
{
DateTimeFormatInfo current = CultureInfo.CurrentCulture.DateTimeFormat;
lock (cacheLock)
{
DateTimeFormatInfo ret;
if (!cache.TryGetValue(current, out ret))
{
ret = (DateTimeFormatInfo) current.Clone();
ret.AMDesignator = ret.AMDesignator.ToLower();
ret.PMDesignator = ret.PMDesignator.ToLower();
cache[current] = ret;
}
return ret;
}
}
}
다른 팁
형식 문자열을 두 부분으로 나눈 다음 AM/PM 부분을 소문자로 나눌 수 있습니다.
DateTime now = DateTime.Now;
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mm");
nowString = nowString + now.ToString("tt").ToLower();
그러나 더 우아한 해결책은 DateTimeFormatInfo
사례 당신이 건설하고 교체한다 AMDesignator
그리고 PMDesignator
"AM"및 "PM"이있는 속성 :
DateTimeFormatInfo fi = new DateTimeFormatInfo();
fi.AMDesignator = "am";
fi.PMDesignator = "pm";
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt", fi);
당신은 사용할 수 있습니다 DateTimeFormatInfo
변환의 다른 많은 측면을 사용자 정의하는 인스턴스 a DateTime
a string
.
편집:존의 예는 훨씬 더 나은,그래도 나는 생각한 확장자는 방법은 여전히 이동하는 방법 당신이하지 않아도 반복하는 코드는다.을 제거하고 바꾸기로 치환되고 존의 첫 번째 예에서 확장자는 방법입니다.내 응용 프로그램은 일반적으로 인트라넷 응용 프로그램이 없어요 걱정이 아닌 미국의 문화.
추가 확장하는 방법에 대해 이렇게 당신입니다.
public static class DateTimeExtensions
{
public static string MyDateFormat( this DateTime dateTime )
{
return dateTime.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
dateTime.ToString("tt").ToLower();
}
}
...
item.PostedOn.MyDateFormat();
편집:다른 아이디어에서 이를 수행하는 방법에 어떻게 형식으로 날짜/시간 다음과 같"Oct.10,2008 년 10:43am CST"C#.
위의 접근법의 문제점은 형식 문자열을 사용하는 주된 이유는 현지화를 가능하게하는 것이며, 지금까지 제공된 접근 방식은 최종 AM 또는 PM을 포함하지 않는 국가 또는 문화에 대해 깨지기 때문입니다. 따라서 내가 한 것은 소문자 AM/PM을 나타내는 추가 형식 시퀀스 'TT'를 이해하는 확장 방법을 작성합니다. 아래 코드는 내 사례에 대해 디버깅되었지만 아직 완벽하지 않을 수 있습니다.
/// <summary>
/// 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
/// </summary>
/// <param name="dt">this DateTime object</param>
/// <param name="formatex">A DateTime format string, with special new abilities, such as TT being a lowercase version of 'tt'</param>
/// <returns>A string representation of value of the current System.DateTime object as specified by format.</returns>
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;
}
이것은 이러한 모든 옵션 중에서 가장 성능이 있어야합니다. 그러나 너무 나쁘기 때문에 그들은 소문자 옵션으로 dateTime 형식 (TT TT?)으로 작동 할 수 없었습니다.
public static string AmPm(this DateTime dt, bool lower = true)
{
return dt.Hour < 12
? (lower ? "am" : "AM")
: (lower ? "pm" : "PM");
}