将var转换为日期值 [英] Turning var to date value

查看:146
本文介绍了将var转换为日期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,其中我将列LearnStartDate的最高值作为var earliestStart。但是,由于我想对这个值做什么,它需要是一个日期格式。我正在努力使用datetime转换它,所以想知道
,如果有更好的方法?正如您将从最后一位看到的那样,可能需要也可能不需要,我将earliestStart值添加到表中。

I have the below code where I am getting the top value of the column LearnStartDate as var earliestStart. However, due to what I want to do with this value, it needs to be of a date format. I am struggling to get it to do so using datetime Convert, so wondered if there's a better way? As you'll see from the last bit, which may or may not be needed, I add the earliestStart value to a table.

           DataView dv = dataTable_Latest.DefaultView;
            dv.Sort = "LearnStartDate";
            DataTable sorted = dv.ToTable();



            var earliestStart = from latest in sorted.AsEnumerable().Take(1)
                                select new
                                {
                                    EarliestStartDate = latest.Field<string>("LearnStartDate")
                                };



            DataTable date = earliestStart.ToTable();

推荐答案

这取决于数据在数据库中的存储方式。如果DB中的列是DATE,DATETIME等,那么您可以直接将该值作为DateTime读取。

It depends upon how that data is stored in your DB. If the column in the DB is a DATE, DATETIME, etc then you can just read the value directly as a DateTime.

latest.Field<DateTime>("LearnStartDate")

这是最好的选择,因为DB会强制执行这样的事实,即它是一个日期,格式本身并不重要。但是,如果将列定义为VARCHAR,那么您将遇到格式化问题。 SQL的文化信息确定
格式化日期,因此让SQL返回日期的字符串版本意味着您的代码必须就格式达成一致。如果您可以同意格式,那么您可以使用DateTime.TryParse来解析它。不幸的是,这完全取决于您的数据库实现和
代码,以保持同步。如果你不这样做,你将在列中获得不同的格式,并且解析变得相当困难。您可以从基本的TryParse调用开始,但很可能它会因某些格式而失败,因此您需要开始查找特定格式的
。如果字符串与这些格式中的任何一种都不匹配,那么你就不幸了。

This is the best option because the DB will enforce the fact that it is a date and the format itself doesn't matter. However if you have the column defined as a VARCHAR then you are going to run into issues with formatting. SQL's culture info determines the formatting of date and so having SQL return a string version of a date means your code has to agree on the format. If you can agree on the format then you can use DateTime.TryParse to parse it. Unfortunately this is all on your DB implementation and your code to keep things in sync. If you don't then you'll get different formats in the columns and parsing that becomes quite a bit harder. You can start with the basic TryParse call but most likely it'll fail for some formats so you then need to start looking for particular formats. If the string doesn't match any of those formats then you're out of luck.

总之,如果可能的话,使用DATE / DATETIME列。然后将值读取为DateTime并完成。

In summary, use a DATE/DATETIME column if at all possible. Then just have the value read as a DateTime and you're done.


这篇关于将var转换为日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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