不同格式日期的总小时数. C# [英] Sum hours from different formatted dates. C#

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

问题描述

我有问题.我需要用代码总结在办公室工作的时间.我从SQL Server获得的日期没问题,但是我有不同的格式.例如: 2019. 09. 23. 14:54:23 2019.09.23 14:54:23 2019-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#中,提供了一堆方法将包含多种格式的日期时间的字符串转换为统一的DateTime对象.这些方法可以识别很多标准日期时间格式,如果您与它们不同,您甚至可以提供自己的格式.

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(),除非您完全确定格式正确,否则建议仅使用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对象,它将不再具有与之关联的格式.它是一个structure,因此仅具有成员变量和方法.因此,要计算总时数等,可以使用提供的方法.

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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