問題描述
我有問題.我需要在代碼中總結在辦公室工作的時間.我從 SQL 服務器獲得的日期沒問題,但我有不同的格式.例如: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#
中,提供了一堆方法可以將包含多種格式的日期時間的字符串轉換成統一的日期時間
對象.這些方法可以識別相當多的標準日期時間格式,如果您的格式與它們不同,您甚至可以提供自己的.
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 aDateTime
object. If operation fails, it'll thrown an exception.DateTime.TryParse()
- Converts a string to aDateTime
object only if possible. Returnstrue
if successful, andfalse
if it fails.DateTime.TryParseExact()
- Converts a string that is in the specified format into aDateTime
object. Returnstrue
if successful, andfalse
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.Days
、TimeSpan.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
相反,當您在數據庫中存儲數據時,您必須再次使用標準格式,例如 datetime
或 datetime2
.建議您使用 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#的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!