如何将格式为"dd/MM/yyyy"的日期字符串转换为OS当前区域性日期格式 [英] How to Convert a Date String with Format “dd/MM/yyyy” to OS Current Culture Date Format

查看:111
本文介绍了如何将格式为"dd/MM/yyyy"的日期字符串转换为OS当前区域性日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串具有"dd/MM/yyyy"格式的值,例如"04/10/2012".这应该转换为带有当前操作系统文化的日期.

我已经尝试将以下字符串与朝鲜语作为OS的当前文化使用,其中日期格式为yyyy-MM-dd,我的代码未获得正确的月值,它将月值与日互换:

输入:"04/10/2012"
产出:2012-04-10

代码:

 DateTime DT;
            字符串 dt = " ;
            
            DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
            DT = Convert.ToDateTime(字符串 .Format("  + DateInfo .ShortDatePattern +  }",dt.Trim()) ,CultureInfo .CurrentCulture);
            MessageBox.Show("  + DT.ToShortDateString()); 


我该如何解决?

解决方案

 DateTime DT;
            字符串 dt = " ;
            
            DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
            DT = Convert.ToDateTime(字符串 .Format(" ,dt.Trim()),CultureInfo .CurrentCulture);
            MessageBox.Show("  + DT.ToShortDateString()); 


string dt = "04/10/2012";
DateTime DT = DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());


请注意,如果您的"dt"字符串采用其他格式,则此方法将不起作用-潘多拉魔药盒将打开...

A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.

I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:

Input: "04/10/2012"
Output: 2012-04-10

Code:

DateTime DT;
            string dt = "04/10/2012";
            
            DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
            DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
            MessageBox.Show("Date: " + DT.ToShortDateString());


How I ca fix that ?

解决方案

DateTime DT;
            string dt = "04/10/2012";
            
            DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
            DT = Convert.ToDateTime(String.Format ("{0:dd/MM/yyyy}", dt.Trim ()), CultureInfo .CurrentCulture);
            MessageBox.Show("Date: " + DT.ToShortDateString());


string dt = "04/10/2012";
DateTime DT = DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());


Please note that this will not work if your "dt" string is in a different format - the Pandora''s Box of Pain will open...


这篇关于如何将格式为"dd/MM/yyyy"的日期字符串转换为OS当前区域性日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆