来自不同格式日期的总小时数.C#

Sum hours from different formatted dates. C#(来自不同格式日期的总小时数.C#)

本文介绍了来自不同格式日期的总小时数.C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.我需要在代码中总结在办公室工作的时间.我从 SQL 服务器获得的日期没问题,但我有不同的格式.例如:2019.09. 23. 14:54:232019.09.23 14:54:232019-09-23 14:54:23;我想总结工作时间.不分年份.示例如下:

I have a problem. I need to sum hours worked in an office in a code. The dates i get from SQL server thats no problem but i have different formats. For example: 2019. 09. 23. 14:54:23, 2019.09.23 14:54:23 or 2019-09-23 14:54:23; And i want to sum hours worked in result. No matter the year. Heres the example:

try
        {

            string betölt = "SELECT * from munkaorak where";
            if (cbTech.Text != "")
            {
                betölt += " Munkaszam='" + cbMunka.Text + "' AND Részfolyamat='" + cbRész.Text + "' AND TechKod='" + cbTech.Text + "'";
            }
            else if (cbRész.Text != "")
            {
                betölt += " Munkaszam='" + cbMunka.Text + "' AND Részfolyamat='" + cbRész.Text + "'";
            }
            else if(cbMunka.Text !="")
            {
                betölt += " Munkaszam='" + cbMunka.Text + "'";
            }
            betölt += " order by ID DESC";
            MySqlCommand name = new MySqlCommand(betölt, kapcsolat);
            kapcsolat.Open();
            olvasó = name.ExecuteReader();
            int összora = 0;

            if (olvasó.HasRows)
            {
                while (olvasó.Read())
                {
                    if (olvasó.GetString(7) != "Befejezés: ")
                    {
                        string[] aha = olvasó.GetString(6).Split(' ');
                        string kezdes = aha[4];
                        string[] kezd = kezdes.Split(':');
                        int kezdoido = Convert.ToInt32(kezd[0]) * 60 * 60 + Convert.ToInt32(kezd[1]) * 60 + Convert.ToInt32(kezd[2]);

                        int befejezoido = 0;
                        string aha22 = "";
                        if (olvasó.GetString(7).IndexOf('-') >= 0)
                        {
                            string[] aha2 = olvasó.GetString(7).Split(' ');
                            string befejezes = aha2[1];
                            string[] bef = befejezes.Split(':');
                            aha22 = aha2[0].Split('-')[2];
                            befejezoido = Convert.ToInt32(bef[0]) * 60 * 60 + Convert.ToInt32(bef[1]) * 60 + Convert.ToInt32(bef[2]);
                        }
                        else
                        {
                            string[] aha2 = olvasó.GetString(7).Split(' ');
                            string befejezes = aha2[4];
                            string[] bef = befejezes.Split(':');
                            aha22 = aha2[3];
                            befejezoido = Convert.ToInt32(bef[0]) * 60 * 60 + Convert.ToInt32(bef[1]) * 60 + Convert.ToInt32(bef[2]);
                        }                          

                        string dolgozott = "";
                        if (aha[3].Replace(".", "") == aha22.Replace(".", ""))
                        {
                            dolgozott = mpbolora(befejezoido - kezdoido);
                            összora += befejezoido - kezdoido;
                        }
                        else
                        {
                            dolgozott = mpbolora((86400 - kezdoido) + befejezoido);
                            összora += (86400 - kezdoido) + befejezoido;
                        }
                        string validalo = "";
                        try
                        {
                            string[] validal = olvasó.GetString(9).Split(' ');
                            validalo = validal[0] + " " + validal[1] + " " + validal[2] + validal[3] + validal[4] + " " + validal[5];
                        }
                        catch
                        {
                            validalo = olvasó.GetString(9);
                        }
                        string munkafolyamat = olvasó.GetString(3) + "-" + olvasó.GetString(4) + "-" + olvasó.GetString(5);
                        string[] sorok = { olvasó.GetString(2), dolgozott, olvasó.GetString(6).Replace("Kezdés: ", ""), olvasó.GetString(7).Replace("Befejezés: ", ""), olvasó.GetString(8), validalo, munkafolyamat };
                        var lv = new ListViewItem(sorok);
                        lvStat.Items.Add(lv);
                    }


                }
            }
            else
            {
                kapcsolat.Close();
                MessageBox.Show("Nincs adat!", "Figyelem");
            }
            kapcsolat.Close();
            lblÖssz.Text = "Összesen ledolgozott órák: " + mpbolora(összora);
        }
        catch (Exception a)
        {
            MessageBox.Show(a.Message);
            kapcsolat.Close();
        }
        kapcsolat.Close();

它可以工作,但是当出现不同的格式时,由于-"或空格而无法正常工作.请帮忙!

It worked but when different formats appeared its not working because '-' or spaces. Please help!

推荐答案

C#中,提供了一堆方法可以将包含多种格式的日期时间的字符串转换成统一的日期时间 对象.这些方法可以识别相当多的标准日期时间格式,如果您的格式与它们不同,您甚至可以提供自己的.

In C#, there is a bunch of methods provided to convert strings that contain date times in many formats into a unified DateTime object. These methods can recognize quite a few standard date time formats, and if yours differ from them, you can even provide your own.

  • DateTime.Parse() - 将字符串转换为 DateTime 对象.如果操作失败,则会抛出异常.
  • DateTime.TryParse() - 仅在可能的情况下将字符串转换为 DateTime 对象.成功返回true,失败返回false.
  • DateTime.TryParseExact() - 将指定格式的字符串转换为 DateTime 对象.如果成功则返回 true,否则返回 false.
  • DateTime.Parse() - Converts a string to a DateTime object. If operation fails, it'll thrown an exception.
  • DateTime.TryParse() - Converts a string to a DateTime object only if possible. Returns true if successful, and false if it fails.
  • DateTime.TryParseExact() - Converts a string that is in the specified format into a DateTime object. Returns true if successful, and false otherwise.

在您的情况下,您可以使用 DateTime.TryParse() (推荐使用 DateTime.Parse() 除非您绝对确定格式是正确)像这样:

In your case, you can use DateTime.TryParse() (which is recommended over simply using DateTime.Parse() unless you're absolutely sure the format is correct) like so:

var dtStr1 = " 2019. 09. 23. 14:54:23";
var dtStr2 = "2019.09.23 14:54:23";
var dtStr3 = "2019-09-23 14:54:23";

DateTime.TryParse(dtStr1, out DateTime dt1);
DateTime.TryParse(dtStr2, out DateTime dt2);
DateTime.TryParse(dtStr3, out DateTime dt3);

一旦转换为 DateTime 对象,它就不再具有与之关联的格式.它是一个结构,因此只有成员变量和方法.因此,要计算总小时数等,您可以使用提供的方法.

Once converted to a DateTime object, it no longer has a format associated with it. It's a structure, and hence only has member variables and methods. So to calculate total hours etc. you can use provided methods.

假设您想计算一天工作开始和结束之间的时间.您可以将它们转换为 DateTime 对象,然后从其他对象中减去一个,这将给您一个 TimeSpam 对象.

Say you want to calculate time between day's work start and end. You can convert those into DateTime objects, then subtract one from the others which will give you a TimeSpam object.

var dtStrStart = "2019.09.23 08:23:12";
var dtStrEnd = "2019.09.23 16:17:28";

DateTime.TryParse(dtStrStart, out DateTime dtStart);
DateTime.TryParse(dtStrEnd, out DateTime dtEnd);

var diff = dtEnd - dtStart;

现在,TimeSpan 对象,也就是这里的 diff,将为您提供一系列不同的属性,以小时、分钟等为单位.

Now the TimeSpan object, which is diff here, will give you a bunch of properties with difference in hours, minutes etc.

TimeSpan.DaysTimeSpan.Minutes 等会以天、分钟等形式为您提供时间.

The TimeSpan.Days, TimeSpan.Minutes etc will give you the time in days, minutes etc.

Console.WriteLine(diff.Days);
Console.WriteLine(diff.Hours);
Console.WriteLine(diff.Minutes);
Console.WriteLine(diff.Seconds);
Console.WriteLine(diff.Milliseconds);

输出:

0

7

54

16

0

TimeSpan.TotalMinutes 等将为您提供相应单位的整个时间段.

The TimeSpan.TotalMinutes etc will give you the entire time period in respective units.

Console.WriteLine(diff.TotalDays);
Console.WriteLine(diff.TotalHours);
Console.WriteLine(diff.TotalMinutes);
Console.WriteLine(diff.TotalSeconds);
Console.WriteLine(diff.TotalMilliseconds);

输出:

0.329351851851852

0.329351851851852

7.90444444444444

7.90444444444444

474.266666666667

474.266666666667

28456

28456000

相反,当您在数据库中存储数据时,您必须再次使用标准格式,例如 datetimedatetime2.建议您使用 datetime2,更多信息.

And conversely, when you're storing data in the database, you must again use a standard format, such as datetime or datetime2. It's advised you use datetime2, more info here.

这篇关于来自不同格式日期的总小时数.C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:来自不同格式日期的总小时数.C#

基础教程推荐