日時形式のみを使用して、日付時刻の AM/PM を小文字で取得します
-
20-08-2019 - |
質問
AM/PM 指定子を含むカスタム DateTime 形式を取得する必要がありますが、「AM」または「PM」を小文字にしたいです それなし 残りの文字を小文字にします。
正規表現を使用せずに単一の形式を使用することは可能ですか?
私が今持っているものは次のとおりです。
item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt")
現時点での出力例は次のようになります。 2009 年 1 月 31 日土曜日、午後 1 時 34 分
解決
私は個人的には二つの部分でそれをフォーマットします:TOLOWERと非AM / PMの部分、およびAM / PMの一部をます:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
item.PostedOn.ToString("tt").ToLower();
(私は秒で調査します)別のオプションは、現在のDateTimeFormatInfoをつかむコピーを作成し、小文字バージョンに午前/午後の指定子を設定することです。その後、通常のフォーマットにその書式情報を使用します。あなたはの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
を持つプロパティ」それぞれ午前」と "午後" ます:
DateTimeFormatInfo fi = new DateTimeFormatInfo();
fi.AMDesignator = "am";
fi.PMDesignator = "pm";
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt", fi);
あなたはDateTimeFormatInfo
にDateTime
を変換する他の多くの側面をカスタマイズするstring
インスタンスを使用することができます。
編集:Jon の例の方がはるかに優れていますが、どこでもコードを繰り返す必要がないように、拡張メソッドの方がまだ優れていると思います。replace を削除し、拡張メソッドの所定の位置に Jon の最初の例を置き換えました。私のアプリは通常イントラネット アプリなので、米国以外の文化について心配する必要はありません。
これを行うための拡張メソッドを追加します。
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();
編集:これを行う方法に関するその他のアイデアは、 DateTime を「10 月」のようにフォーマットする方法10, 2008 10:43am CST" (C#).
上記のアプローチの問題点は、フォーマット文字列を使用する主な理由は、ローカライズを可能にするために、そしてこれまでのアプローチは、最終的な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");
}