简体   繁体   English

DateTime从MMM-yyyy转换为dd-MM-yyyy或yyyy-MM-dd

[英]DateTime Convert from MMM-yyyy to dd-MM-yyyy or yyyy-MM-dd

I'm submitting date value from view in format MMM-yyyy ie "Apr-2019" as string. 我以格式MMM-yyyy提交日期值,即“Apr-2019”作为字符串。 I need to get the string value converted into .Net supported date format like dd-MM-yyyy or yyyy-MM-dd. 我需要将字符串值转换为.Net支持的日期格式,如dd-MM-yyyy或yyyy-MM-dd。 Here dd will be first day of the month. 这里dd将是这个月的第一天。

I've already searched stackoverflow datetime conversion problems, but those all described about three part date conversion problems. 我已经搜索了stackoverflow日期时间转换问题,但是那些都描述了三部分日期转换问题。 If I try to parse the string adding dd part (ie 01-Apr-2019), it says- "String was not recognized as a valid DateTime". 如果我尝试解析添加dd部分的字符串(即01-Apr-2019),它会说 - “字符串未被识别为有效的DateTime”。 But if I use numeric value of MMM with that string, then the string is recognizable and I can use ParseExact- 但是如果我使用MMM的数值和该字符串,那么该字符串是可识别的,我可以使用ParseExact-

//string dt = "01-Apr-2019";//Not recognizable string format
string dt = "01-04-2019";//Recognizable string format
DateTime newDt = DateTime.ParseExact(dt, "dd-MM-yyyy", CultureInfo.InvariantCulture);

So, is there any built in method/class in .Net which I can use to convert "Apr-2019" format value and achieve my dd-MM-yyyy or yyyy-MM-dd or any other .Net recognizable format? 那么,.Net中是否有内置的方法/类,我可以使用它来转换“Apr-2019”格式值并实现我的dd-MM-yyyy或yyyy-MM-dd或任何其他.Net可识别格式?

Why do you need to convert the string? 为什么需要转换字符串?

Just do parse exact on the format you want: 只需按照您想要的格式进行精确解析:

DateTime newDt = DateTime.ParseExact(dt, "MMM-yyyy", CultureInfo.InvariantCulture);

It will set the day to the first of the month 它将把这一天设置为该月的第一天

Use 采用

DateTime.ParseExact(dt, "MMM-yyyy", CultureInfo.InvariantCulture)

This will give you first of the month anyway. 无论如何,这将给你一个月的第一个。

OP wants to convert the string with the day as well. OP想要将日期转换为字符串。 Use the below code, you can use the format dd-MMM-yyyy . 使用以下代码,您可以使用格式dd-MMM-yyyy

string dt = "01-Apr-2019";
DateTime newDt = DateTime.ParseExact(dt, "dd-MMM-yyyy", CultureInfo.InvariantCulture);

I have tried the below code it was works for me. 我尝试了以下代码,它对我有用。 Could you try this one. 你能试试这个吗? string strDt = "Sep-2019"; string strDt =“Sep-2019”; DateTime dt = Convert.ToDateTime(strDt).AddDays(0.0); DateTime dt = Convert.ToDateTime(strDt).AddDays(0.0);

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

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