How to get date only if time is 00:00:00 from DateTime C #

I want to convert a DateTime object to a string. I want to achieve the following goals:

  • Get the date only from it if the time is 00:00:00.
  • Get the date and time if present.
  • I want to achieve this using CurrentCulture.DateTimeFormatand Convert.ToString(DateTime, IFormatProvider)otherwise I know how to use the .ToString()Extension method for this .

I have tried the 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 signal 09-Oct-2015 11:00 AM. I want 09-Oct-2015 11:00 AMif time is, and 09-Oct-2015if time does not exist.

But the above line only gives me the date, even if the time is present with the date.

+4
source share
2 answers

.

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;
            }
        }
+1

, :

var dt = x.ExpectedJoiningDate;
string x = (dt.TimeOfDay == TimeSpan.Zero)?dt.ToShortDateString():dt.ToString();

PS: ToString, . , , . https://msdn.microsoft.com/en-us/library/aa326720(v=vs.71).aspx.


, OP Convert.ToString. , . ? Convert.ToString:

public static string ToString(DateTime value, IFormatProvider provider)
{
    return value.ToString(provider);
}

, , .

, , , IFormatProvider , , . , congrats, , , Convert.ToString.

+8

All Articles