开发者

C# Format String as Date [closed]

开发者 https://www.devze.com 2023-01-12 11:20 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incompl开发者_运维问答ete, overly broad, or rhetorical andcannot be reasonably answered in its current form.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incompl开发者_运维问答ete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 9 years ago.

I have a DetailsView with a TextBox bound to a DateTime column. The value of the column is presented in the format "dd/mm/yyyy hh:mm:ss". I need it to be displayed in the format "yyyy/mm/dd". I had though that the best way may be to format the string in the DataBound event. Problem is, I can't seem to find a way to format the string as a date. The String.Format won't do it. If I had the string as a DateTime then I could use the DateTime.Format method. I could create a datetime variable by parsing the various elements of the string but I can't help but think there must be an easier way?

Thanks

Rob.


Something like this should work:

public static string GetDateString(string date)
{
    DateTime theDate;
    if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss", 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
    {
        // the string was successfully parsed into theDate
        return theDate.ToString("yyyy'/'MM'/'dd");
    }
    else
    {
        // the parsing failed, return some sensible default value
        return "Couldn't read the date";
    }
}


string testDate = "19/08/2010 06:19:30";
DateTime asDate = DateTime.ParseExact(testDate,
   "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(asDate.ToString("yyyy/MM/dd"));


Convert it to a DateTime then then use string.format to format it how you want.

    DateTime MyDateTime = Convertto.Date"01/12/2004 00:35:23",
   "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    string.Format("The Date is:{0}", "yyyy/MM/dd",MyDateTime);


DataFormatString="{0:d}". You can give this property to your field. Write this in ASP page


Instead of using TextBox You may consider to use MaskedTextBox, then only thing that You do is to set the mask (format).

Read More about MaskedTextBox

0

精彩评论

暂无评论...
验证码 换一张
取 消