DateTime问题,当天< = 12 [英] DateTime problem when day <= 12

查看:121
本文介绍了DateTime问题,当天< = 12的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了很多,不足以编写可怕的代码来操纵字符串,我想问是否有人知道一个很好的排序方式:

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:

我有一堆日期字符串,我正在拉出的单元格,如:

I have a bunch of date strings in cells that I'm pulling out such as:

03/05/2011

27/05/2011

31/05/2011

03/05/2011

09/05/2011

31 / 05/2011

等。

03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.

当我读任何一天可以被解释为一个月 - 即条目1,4和5以上 - 它被作为一个DateTime交换日期和月份。

While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.

例如,03/05/2011以DateTime05/03 / 2011 00:00:00
其他人都阅读完善地提供了一个简单的字符串27/05/2011。

For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00" The others are all read and nicely provide me with a simple string of "27/05/2011".

我从Excel获取此信息,使用

I'm getting this info from Excel, using

((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()

如果我像我的其他行一样尝试Value2,它会读取奇数日期如40607,但再次读取其他日期。

If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.

推荐答案

如果您使用 DateTime.ParseExact 功能将一个字符串转换为一个 DateTime 对象,您可以指定日期使用的特定格式(如日/月/年),而无需执行任何字符串操作任何。

If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.

示例:

var dateString = "03/05/2011";

var format = "dd/MM/yyyy";

var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

可以找到有关自定义日期和时间格式字符串的更多信息 here

More information on custom Date and Time format strings can be found here.

编辑:尝试使用 DateTime.FromOADate 方法转换由 Range.Value2 属性为 DateTime 对象,例如如下所示:

Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:

var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);

这篇关于DateTime问题,当天< = 12的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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