使用格式将字符串转换为日期 (VB.net)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36434079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:47:42  来源:igfitidea点击:

Convert string to date with format (VB.net)

vb.netstringdate

提问by TobiasKnudsen

I have a string with a date in this format. "24-11-2015" or "dd-MM-yyyy". I need to convert this to a date with this format. "2015-11-24" or "yyyy-MM-dd". I've tried several ways, and all of them rely on my system format for this to work. If i run my program on a computer with english time format this works.

我有一个带有这种格式的日期的字符串。“24-11-2015”或“dd-MM-yyyy”。我需要将其转换为这种格式的日期。“2015-11-24”或“yyyy-MM-dd”。我已经尝试了几种方法,所有方法都依赖于我的系统格式才能正常工作。如果我在具有英语时间格式的计算机上运行我的程序,这将起作用。

Date.ParseExact("24-11-2015", "dd-MM-yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)

But if i run it on a computer running danish format i get error because there is no 24th month. How do i make the date format independent of my system time format.

但是,如果我在运行丹麦格式的计算机上运行它,则会出现错误,因为没有第 24 个月。如何使日期格式独立于我的系统时间格式。

回答by Claudius

Solution:

解决方案:

Dim dateTime As String = "24-11-2015"
Dim dt As DateTime = Convert.ToDateTime(dateTime)
Console.WriteLine("{0}-{1}-{2}", dt.Year, dt.Month.ToString("D2"), dt.Day.ToString("D2"))

Solution 2:

解决方案2:

Dim dateTime As String = "24-11-2015"
Dim dt As DateTime = Convert.ToDateTime(dateTime)
Dim format As String = "yyyy-MM-dd"
Dim str As String = dt.ToString(format)
Console.WriteLine(str)

You can also try Formatting Date and Time for a Specific Culture.

您还可以尝试格式化特定文化的日期和时间