从excel读取时,以字符串格式比较两个日期 [英] compare two dates in string format while reading from excel

查看:573
本文介绍了从excel读取时,以字符串格式比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我在excel字段中有两个日期字段。我想比较这两个领域。但由于excel字段的值是字符串转换为DateTime可能会导致问题。那么有什么方法可以比较它们吗?我认为这是不可能的,即使它不会100%安全失败。它的预感并不多。请告诉我是否有办法

Hi,

I have two date fields in excel field. I want to compare these two fields. But since the value of excel fields is string convert them into DateTime may cause problem. So is there any way to compare them? I think its not possible, even if it is it won't be 100 % fail safe. Its my hunch nothing much. Please let me know if there is a way

推荐答案

不,这不可能,而且肯定不是安全 - 你真的想转换它们首先是一个DateTime值,然后进行比较。



如果日期是ISO格式,那么可以进行字符串比较:yyyy-MM-dd

因为字符串比较在第一个差异处停止,并使用字符比较来确定顺序。但是......如果一个日期是2014-01-3而另一个是2014-01-14,那么字符串比较就会得到错误的顺序。



你可以手动处理字符串并对各个部分进行比较 - 但是你正在复制将它转换为DateTime的工作! :笑:
No, it's not really possible, and it certainly isn't "safe" - you really do want to convert them to a DateTime value first and then do the comparison.

It's all ok to do a string compare if the dates are in ISO format: yyyy-MM-dd
Because string comparisons stop at the first difference and use character comparisons to determine order. But...if one date is 2014-01-3 and the other is 2014-01-14 then a string comparison gets them in the wrong order.

You could manually process the string and do the comparison on the various parts - but then you are duplicating the work that converting it to a DateTime does anyway! :laugh:


如果您要比较的字段有数据格式。

您可以确定该字段将采用日期时间格式。



有关字段/行/列的数据格式的更多信息:格式化 - 在Excel中的日期 [ ^ ]



然后你可以做DateTime.Parse(你的字段)。



如果你有两个DateTime结构实例,你可以使用运算符== ,!=和>,<,> =,< =分别在后来,更早,不早,不迟的意义上。此外,您可以使用减法运算符( - ),它以System.TimeSpan的形式返回结果。这是一套全面的操作员,可以满足您的所有比较需求。
If you have Data format on the fields you want to compare.
You can know for sure the field will be in a datetime format.

for more info on data format of fields/rows/columns: format-a-date in excel[^]

then you could do DateTime.Parse(your field).

When you have two instances of DateTime structure you can use operators "==", "!=" and ">", "<", ">=", "<=" in the sense "later", "earlier", "not earlier", "not later", respectively. Also, you can use subtraction operator ("-") which returns the result in the form of System.TimeSpan. This is a comprehensive set of operators to cover all your comparison needs.


这篇关于从excel读取时,以字符串格式比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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