简体   繁体   English

将自定义字符串转换为DateTime格式的C#最佳方法

[英]C# Best method to convert custom String to DateTime format

What's the best method for converting a custom string to DateTime format? 将自定义字符串转换为DateTime格式的最佳方法是什么?

My custom strings could look any of these... "5d 4h 25m", "4h 25m", or "25m" 我的自定义字符串可能看起来像以下任何一种:“ 5d 4h 25m”,“ 4h 25m”或“ 25m”

You can set any pattern you like and use DateTime.TryParseExact to parse your string to a DateTime object. 您可以设置任何喜欢的模式,并使用DateTime.TryParseExact将您的字符串解析为DateTime对象。

You might want to take a look at this page. 您可能想看看这个页面。

var converted = Convert.ToDateTime(yourString);

If it is possible to store each components individually, you could use TimeSpan. 如果可以分别存储每个组件,则可以使用TimeSpan。

here is a link with details about TimeSpan: http://www.dotnetperls.com/timespan-parse 这是有关TimeSpan的详细信息的链接: http : //www.dotnetperls.com/timespan-parse

On a second note, i would be telling you to create a method that takes your string and splits it in its various components and use each components with DateTime or TimeSpan 第二点,我要告诉您创建一个方法,该方法将您的字符串拆分为各种组件,并将每个组件与DateTime或TimeSpan一起使用

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

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