结合日期是DateTime的日期和时间,时间是一个字符串 [英] Combine date and time when date is a DateTime and time is a string

查看:166
本文介绍了结合日期是DateTime的日期和时间,时间是一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个旧的mysql数据库,其中一个日期被存储(没有时间)作为日期时间,一个时间被存储为一个字符串(没有日期)。

I am working with an old mysql database in which a date is stored (without a time) as a datetime and a time is stored as a string (without a date).

在C#中,我有一个DateTime,值为$ code> 2010-06-25 12:00:00 AM 和一个值为 15:02

In C# I then have a DateTime with a value like 2010-06-25 12:00:00 AM and a String with a value like 15:02.

什么是最简洁的方法来组合这些没有很多开销?

What is the most concise way to combine these without a lot of overhead?

我已经尝试了一些方法,包括:

I have tried a few methods including:

DateTime NewDateTime = DateTime.Parse(OldDateTime.ToString("yyyy-MM-dd ") + TimeString);

我不喜欢将现有的DateTime转换为字符串并附加时间。

I dislike converting the existing DateTime to a string and appending the time.

我可以将时间字符串转换为日期,但是我得到今天的日期,并将其添加到旧的datetime的一些ticks是不正确的。

I can convert the time string to a date, but then I get today's date and adding it as a number of ticks to the old datetime is incorrect.

注意:不要担心验证,它在其他地方完成。这个时间用24小时的格式表示,没有秒。

推荐答案

你可以使用 TimeSpan.Parse 来解析时间,然后将结果添加到日期:

You can use TimeSpan.Parse to parse the time, and then add the result to the date:

DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));

这篇关于结合日期是DateTime的日期和时间,时间是一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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