简体   繁体   English

我应该使用哪种数据类型来读取年月和年周值? C#

[英]What data type should I use for reading year-month and year-week values ? c#

Technology is winforms, using c#, database is SQlite. 技术是winforms,使用c#,数据库是SQlite。

I'm taking values from the DB, transfering them into lists, and subsequently populating a listview with those lists. 我从数据库中获取值,将其传输到列表中,然后使用这些列表填充listview。

I have two columns for dates. 我有两列日期。 One has values with the format of Year and month (YYYY-MM) and the other is Year and Week (YYYY-WW). 一个具有年和月(YYYY-MM)格式的值,另一个是年和周(YYYY-WW)的值。

Problem: 问题:

But in the listview these values show up with slashes in between them, ie January 2001 is written as 1/1/2001 12:00 am. 但是在列表视图中,这些值之间以斜杠显示,即2001年1月写为1/1/2001 12:00 am。 The 31st week in 2002 is written as 3/1/2002 12:00 am. 2002年第31周写为2002年3月1日上午12:00。

I don't want the TIME or slashes in the output. 我不想在输出中使用TIME或斜杠。 (First 2 lists are the output in listview, with the errors i mentioned above. The second 2 columns are how the data is supposed to look). (前2个列表是listview的输出,上面有我提到的错误。后2个列是数据的外观)。

在此处输入图片说明

What the problem is caused by : I use the DateTime datatype to store the values from these columns. 是什么引起的问题 :我使用DateTime数据类型存储这些列中的值。 Is there any datatype which will just output these values in year-month and year week format, instead of displaying slashes and time. 是否有任何数据类型将仅以年-月和年-周格式输出这些值,而不显示斜线和时间。 If I try using int, the these columns don't even get read so can't use that. 如果我尝试使用int,这些列甚至都不会被读取,因此不能使用它。

Code: (Just focus on the yyyymm part) 代码:(仅关注yyyymm部分)

 string sql6 = "select YYMM, TotalTrans  from t2 where cast(TotalTrans as int) < 1000";
       SQLiteCommand command3 = new SQLiteCommand(sql6, sqlite_conn);


       SQLiteDataReader reader3 = command3.ExecuteReader();

       while (reader3.Read())
       {

           int TotalTrans;
           DateTime yyyymm;  //Right here:

           if (DateTime.TryParse(reader3["YYMM"].ToString(), out yyyymm) && int.TryParse(reader3["TotalTrans"].ToString(), out TotalTrans))
           {
               YYMM.Add(yyyymm);
               TotalTransIrregularities.Add(TotalTrans);
           }
       }

For your YYMM column, you can use a DateTime like you are. 对于YYMM列,您可以像YYMM一样使用DateTime When you output it as a string, you should use the yyyy-MM format. 以字符串形式输出时,应使用yyyy-MM格式。

Your YYWW column is more complicated, because DateTime doesn't support parsing weeks. 您的YYWW列更为复杂,因为DateTime不支持解析周。 I'd recommend that you create your own type, and display it in the ISO standard way of, eg 2002-W31 . 我建议您创建自己的类型,并以ISO标准的方式显示它,例如2002-W31 That type might look like this: 该类型可能如下所示:

public struct YearWeek
{
    private static readonly Regex parseRegex =
                            new Regex(@"^(?<year>\d{4})-W?(?<week>\d{2})$");
    public int Year { get; private set; }
    public int Week { get; private set; }
    public YearWeek(int year, int week) : this()
    {
        this.Year = year;
        this.Week = week;
    }
    public static bool TryParse(string s, out YearWeek result)
    {
        var match = parseRegex.Match(s);
        if (match.Success)
        {
            result = new YearWeek(int.Parse(match.Groups["year"].Value),
                                int.Parse(match.Groups["week"].Value));
            return true;
        }
        else
        {
            result = default(YearWeek);
            return false;
        }
    }
    public static YearWeek Parse(string s)
    {
        YearWeek result;
        if (TryParse(s, out result))
            return result;
        else
            throw new ArgumentException("s");
    }
    public override string ToString()
    {
        return string.Format("{0:0000}-W{1:00}", Year, Week);
    }
}

You can use ToString() function on DateTime Types to get the required format of the string. 您可以在DateTime Types上使用ToString()函数来获取所需的字符串格式。

Example: 例:

DateTime dt=DateTime.Now;
dt.ToString("yyyy"); => gives you year => 2013
dt.ToString("MM");=>gives you month=>11
dt.ToString("dd");=>gives you Date=>19

Solution 1 : For getting Date in format of yyyy-MM 解决方案1:yyyy-MM格式获取Date

String yearmonth=yyyymm.ToString("yyyy-MM");

Solution 2: for getting the Date in format of yyyy-WW 解决方案2:yyyy-WW格式获取Date

inorder to get the WeekNumber you need to use Calendar . 为了获得WeekNumber您需要使用Calendar You can invoke GetWeekOfYear() method on Calendar object to get the Current Week Number . 您可以在Calendar对象上调用GetWeekOfYear()方法来获取当前Week Number

using System.Globalization;
Calendar myCal = CultureInfo.InvariantCulture.Calendar;
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
String yearweek = yyyymm.ToString("yyyy") +"-"+ myCal.GetWeekOfYear(yyyymm, dfi.CalendarWeekRule, dfi.FirstDayOfWeek).ToString();

You can use format string in DateTime.ToString(...) method. 您可以在DateTime.ToString(...)方法中使用格式字符串。 Use this article to compose your format string http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx . 使用本文撰写您的格式字符串http://msdn.microsoft.com/zh-cn/library/8kb3ddd4(v=vs.110).aspx To get DateTime structure from custom datetime string use DateTime.ParseExact(...) method. 要从自定义日期时间字符串获取DateTime结构,请使用DateTime.ParseExact(...)方法。

For example year-month format string will be "yyyy-MM" 例如,年月格式字符串将为"yyyy-MM"

As for the week number, the case is little more difficult. 至于星期几,情况就难多了。 There is no week number format string but you easily can get it from date. 没有周数格式字符串,但是您可以轻松地从日期获取它。 See the answer for this question: Week number of a year in dateformat It has everything you need. 请参阅以下问题的答案: dateformat中一年的星期数它具有您需要的一切。

Use the STRFTIME function in your query. 在查询中使用STRFTIME函数。

sqlite> select strftime('%Y-%m', 'now');
2013-11
sqlite> select strftime('%Y-%W', 'now');
2013-46

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

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