系统日期格式为dd / MM / yyyy时,将字符串的日期格式转换为日期时间MM / dd / yyyy

时间:2015-02-05 04:11:54

标签: c# wpf

当系统日期格式为'dd / MM / yyyy'时,我需要将字符串格式'MM / dd / yyyy'的日期转换为日期时间格式'MM / dd / yyyy'。

5 个答案:

答案 0 :(得分:2)

DateTime将日期存储为数值,而不是字符串。因此,要求DateTime 类型的格式'MM / dd / yyyy'没有多大意义。如果您在WPF控件中显示日期,它将默认显示符合系统日期格式的字符串。但这只是一个显示字符串,您可以使用上面链接中提到的格式字符串进行操作。使用@ Sajeetharan的代码将在内部创建一个具有正确值的DateTime结构。如何显示它取决于您和您的字符串格式选择。

存储在“datetime”类型的数据库列中的日期也是如此。该值以数字形式存储。您的查询编辑器将显示可能与系统设置格式相同的值。如果日期存储为字符串,那么@ Sajeetharan的代码是将数据库字符串转换为DateTime结构的正确方法。

答案 1 :(得分:1)

使用DateTime.ParseExact

DateTime.ParseExact("05/02/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)
                        .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

答案 2 :(得分:1)

这可能有所帮助:

string dateString="05/02/2014";
DateTime txtmyDate = DateTime.ParseExact(dateString, "MM/dd/yyyy",     
CultureInfo.InvariantCulture);

答案 3 :(得分:0)

试试这个

string dateString="05/02/2014";
DateTime txtmyDate =convert.toDateTime(dateString);

答案 4 :(得分:0)

int ParseEnum(TypeReference enumRef, string value)
{
    var enumDef = enumRef.Resolve();
    if (!enumDef.IsEnum)
        throw new InvalidOperationException();

    int? result = null;

    foreach (var v in value.Split(',')) {
        foreach (var field in enumDef.Fields) {
            if (field.Name == "value__")
                continue;
            if (field.Name == v.Trim())
                result = (result ?? 0) | (int)field.Constant;
        }
    }

    if (result.HasValue)
        return result.Value;

    throw new Exception(string.Format("Enum value not found for {0}", value));
}