I want to convert DateTime object to string. What I want to achieve is following things:
CurrentCulture.DateTimeFormat
and Convert.ToString(DateTime, IFormatProvider)
, otherwise I know how to do this using .ToString()
Extension method. I have tried following things:
Thread.CurrentPrincipal = principal;
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = MPAResource.DateFormat;
culture.DateTimeFormat.LongTimePattern = "hh:mm:ss tt";
culture.DateTimeFormat.ShortTimePattern = "hh:mm:ss tt";
culture.DateTimeFormat.FullDateTimePattern = MPAResource.DateTimeFormat;
Thread.CurrentThread.CurrentCulture = culture;
Then:
string x = Convert.ToString(x.ExpectedJoiningDate, CultureInfo.CurrentCulture);
Output is 09-Oct-2015 11:00 AM
. I want 09-Oct-2015 11:00 AM
if time is there and 09-Oct-2015
if time is not there.
But above line gives me only date even if time is present with date.
Seems to me like this is pretty straight forward:
var dt = x.ExpectedJoiningDate;
string x = (dt.TimeOfDay == TimeSpan.Zero)?dt.ToShortDateString():dt.ToString();
PS: you can use a culture as parameter in ToString if you like. See https://msdn.microsoft.com/en-us/library/aa326720(v=vs.71).aspx for details on how to do this.
Tim made the remark that the OP wants to use Convert.ToString
. It doesn't compute, so I refuse. Why doesn't it compute? Here's the code for Convert.ToString
:
public static string ToString(DateTime value, IFormatProvider provider)
{
return value.ToString(provider);
}
Yes people, that's basically the same.
That said, if you're stubborn, I guess you can implement IFormatProvider
in your own little class, change the format provider based on the condition, then pass that instead of the default format provider. Then, congrats, you've created a lot of senseless code that gives the exact same results using Convert.ToString
.
After a while a wrote method for myself.
public static string ConvertToMyDateTimeFormat(Nullable<DateTime> value, CultureInfo IFormateProvider)
{
if (value.HasValue)
{
if (value.Value.TimeOfDay.Ticks > 0)
{
return value.Value.ToString(IFormateProvider);
}
else
{
return value.Value.ToString(IFormateProvider.DateTimeFormat.ShortDatePattern);
}
}
else
{
return string.Empty;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.