如何获取所需格式的日期格式,如“dd / MM / yyyy”,“MMddyyyy”,MMM等 [英] How to get date format in required format like 'dd/MM/yyyy' , 'MMddyyyy', MMM, etc
问题描述
我的日期是MM / dd / yyyy格式,我需要根据输入格式获取日期格式。输入格式将是MMddyyyy,yyyy-MM-dd,MM,MMM,MMMM,yyyy的任何人。
I have date in 'MM/dd/yyyy' format and I need to get date format according input format. Input format will be anyone of 'MMddyyyy', 'yyyy-MM-dd' , MM, MMM, MMMM, yyyy.
格式:'MMddyyyy'::输出应是:'02232015'
Format:'MMddyyyy':: Output Should be: '02232015'
格式:'yyyy-MM-dd'::输出应为:'2015-02-23'
Format:'yyyy-MM-dd':: Output Should be: '2015-02-23'
格式:'yyyy / MM / dd'::输出应为:'2015/02/23'
Format:'yyyy/MM/dd':: Output Should be: '2015/02/23'
格式:'MM' :输出应为:'02'
Format:'MM':: Output Should be: '02'
格式:'MMM'::输出应为:'二月'
Format:'MMM':: Output Should be: 'Feb'
格式:'MMMM'::输出应该是:'二月'
Format:'MMMM':: Output Should be: 'February'
我正在尝试使用
var dateTime = DateTime.ParseExact(date, format, new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.None);
但它不工作。它给出无效的日期格式错误。
But it is not working. It give invalid date format error.
任何人都可以帮助我实现这一点。
So can anyone help me to achieve this.
推荐答案
我觉得你很难将一个字符串解析成一个 DateTime
,而是获得一个<$ c $的具体字符串表示c> DateTime 。
I think you are confusing about parsing a string to a DateTime
with getting a specific string representation of a DateTime
.
如果你想获得一个 DateTime
的文本表示像 2015-02-23
, 2015/02/23
和 February
,你可以使用 .ToString()
方法与基于英语的文化。
If you wanna get a textual representation of a DateTime
(like 2015-02-23
, 2015/02/23
and February
as you said), you can use .ToString()
method with an english-based culture.
对于您的字符串结果的订单,您可以将它们作为;
For your string results with order, you can get them as;
yourDateTimevalue.ToString("MMddyyyy", new CultureInfo("en-US")); // 02232015
yourDateTimevalue.ToString("yyyy-MM-dd", new CultureInfo("en-US")); // 2015-02-23
yourDateTimevalue.ToString("yyyy/MM/dd", new CultureInfo("en-US")); // 2015/02/23
yourDateTimevalue.ToString("MM", new CultureInfo("en-US")); // 02
yourDateTimevalue.ToString("MMM", new CultureInfo("en-US")); // Feb
yourDateTimevalue.ToString("MMMM", new CultureInfo("en-US")); // February
如果您尝试您有这些格式化的字符串,并且您想将这些格式化的字符串解析为 DateTime
,您可以使用这个 DateTime.ParseExact
重载需要 string []
作为格式。
If you try to say like; you have these formatted strings and do you wanna parse these formatted strings to DateTime
, you can use this DateTime.ParseExact
overload that takes string[]
as a format.
var formats = new string[]
{
"MMddyyyy",
"yyyy-MM-dd",
"yyyy/MM/dd",
"MM",
"MMM",
"MMMM"
}
var dateTime = DateTime.ParseExact(date, formats, new CultureInfo("en-US"), DateTimeStyles.None);
这篇关于如何获取所需格式的日期格式,如“dd / MM / yyyy”,“MMddyyyy”,MMM等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!