I know that I could use a format string, but I don\'t want to lose the culture specific representation of the date/time format. E.g.
5/4/2011 | 2:06 PM | ...>
I see only a single solution - you should obtain the current culture display format, patch it so that it meets your requirement and finally format your DateTime value using the patched format string. Here is some sample code:
string pattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
DateTime dt = DateTime.Now;
string[] format = pattern.Split(new string[] { CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator }, StringSplitOptions.None);
string newPattern = string.Empty;
for(int i = 0; i < format.Length; i++) {
newPattern = newPattern + format[i];
if(format[i].Length == 1)
newPattern += format[i];
if(i != format.Length - 1)
newPattern += CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
}
As promised, here is the improved version:
///
/// Extensions for the class.
///
public static class DateTimeExtensions
{
///
/// Provides the same functionality as the ToShortDateString() method, but
/// with leading zeros.
///
/// ToShortDateString: 5/4/2011 |
/// ToShortDateStringZero: 05/04/2011
///
///
/// Source date.
/// Culture safe short date string with leading zeros.
public static string ToShortDateStringZero(this DateTime source)
{
return ToShortStringZero(source,
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern,
CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator);
}
///
/// Provides the same functionality as the ToShortTimeString() method, but
/// with leading zeros.
///
/// ToShortTimeString: 2:06 PM |
/// ToShortTimeStringZero: 02:06 PM
///
///
/// Source date.
/// Culture safe short time string with leading zeros.
public static string ToShortTimeStringZero(this DateTime source)
{
return ToShortStringZero(source,
CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern,
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator);
}
private static string ToShortStringZero(this DateTime source,
string pattern,
string seperator)
{
var format = pattern.Split(new[] {seperator}, StringSplitOptions.None);
var newPattern = string.Empty;
for (var i = 0; i < format.Length; i++)
{
newPattern = newPattern + format[i];
if (format[i].Length == 1)
newPattern += format[i];
if (i != format.Length - 1)
newPattern += seperator;
}
return source.ToString(newPattern, CultureInfo.InvariantCulture);
}
}