locked
DateTime Convert RRS feed

  • Question

  • User-1971168174 posted

    Hi,

    I am trying to get date for today and 10 days back,I am using below code:

    DateTime days = DateTime.Today.AddDays(0);
    DateTime nDaysAgo = DateTime.Today.AddDays(-10);

    Above returns output as : 28-09-2018 00:00:00 but i need to have the date in format ( 9/28/2018 12:00:00 AM)

    Need help! 

    Monday, October 8, 2018 4:50 PM

Answers

  • User839733648 posted

    Hi neerajkumarmodi,

    According to your description, I suggest that you could use the String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", date) function to format your date.

    For more details, you could refer to the code below.

                DateTime days = DateTime.Today.AddDays(0);
                DateTime nDaysAgo = DateTime.Today.AddDays(-10);
                string daysformat = String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", days);
                string nDaysAgoformat = String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", nDaysAgo);
                Response.Write("days:" + daysformat);
                Response.Write("<br/>");
                Response.Write("nDaysAgo:" + nDaysAgo);

    output:

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 7:38 AM

All replies

  • User475983607 posted

    The DateTime is a structure which is numeric.  Below is a string that represents a DateTime and it is dependent on the current culture.

    28-09-2018 00:00:00

    Use the standard DateTIme formats to output a DateTime string in the format you want.

    nDaysAgo.ToString("g");

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    Monday, October 8, 2018 5:03 PM
  • User839733648 posted

    Hi neerajkumarmodi,

    According to your description, I suggest that you could use the String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", date) function to format your date.

    For more details, you could refer to the code below.

                DateTime days = DateTime.Today.AddDays(0);
                DateTime nDaysAgo = DateTime.Today.AddDays(-10);
                string daysformat = String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", days);
                string nDaysAgoformat = String.Format("{0:MM/dd/yyyy hh:mm:ss tt}", nDaysAgo);
                Response.Write("days:" + daysformat);
                Response.Write("<br/>");
                Response.Write("nDaysAgo:" + nDaysAgo);

    output:

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 9, 2018 7:38 AM