简体   繁体   English

如何将日期格式从dd-MMM-yyyy更改为yyyy-MM-dd

[英]how to change date format from dd-MMM-yyyy to yyyy-MM-dd

I can't change date format, I've tried 2 methods but the output is 0001-01-01 我无法更改日期格式,我尝试了2种方法,但输出为0001-01-01

Method 1 方法1

hf_test.Value = "1-Jul-2013";

DateTime date;
var success = DateTime.TryParseExact(hf_test.Value,
    "dd-MMM-yyyy",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out date);

    Resopnse.Write(date.ToString("yyyy-MM-dd"));

Method 2 方法2

        hf_test.Value = "1-Jul-2013";
        Alert.Show(DateTime.ParseExact(hf_test.Value , "dd-MMM-yyyy", culture).ToString("yyyy-MM-dd"));

Output of 0001-01-01 means that your date coud not be parsed. 输出0001-01-01表示不解析您的日期。 The reason is that you've used dd instead of d for a string like "1-Jul-2013" . 原因是您已经使用dd而不是d来表示字符串"1-Jul-2013"

So use 所以用

DateTime date;
bool success = DateTime.TryParseExact(hf_test.Value,
                            "d-MMM-yyyy",
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.None,
                            out date);

You are using the wrong format specifier, your date string is using a single-digit day but you are using the leading 0 format specifier ( dd ). 您使用了错误的格式说明符,您的日期字符串使用的是一位数字日期,但您使用的是前导0格式说明符dd )。 This expects your date string to have the day formatted as 01-31 . 这期望您的日期字符串的日期格式为01-31

You need to use the non-leading 0 format specifier ( d ) which allows single digit days ie 您需要使用开头的0格式说明符d ),该说明符允许一位数的天,即

 d-MMM-yyyy

See Custom Date and Time Format Strings 请参阅自定义日期和时间格式字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM