简体   繁体   English

从数据库计算时间

[英]Calculate Time from Database

I am trying to make my program calculate a break time with data stored in an mysql database.我试图让我的程序使用存储在mysql数据库中的数据计算休息时间。

private void timerpause_Tick(object sender, EventArgs e)
        {
            MySqlConnection conn = DBUtils.GetDBConnection();
            conn.Open();

            MySqlCommand dbrequest = conn.CreateCommand();
            dbrequest.CommandText = "SELECT pstart FROM arbeitszeiten WHERE fullname = '" + textBoxfullname.Text + "' and active = 'JA'";
            string pausebeginn = dbrequest.ExecuteScalar().ToString();

            MySqlCommand dbrequest2 = conn.CreateCommand();
            dbrequest2.CommandText = "SELECT ptotal FROM arbeitszeiten WHERE fullname = '" + textBoxfullname.Text + "' and active = 'JA'";
            string pausenzeit = dbrequest2.ExecuteScalar().ToString();

            TimeSpan pause = Convert.ToDateTime(pausenzeit).TimeOfDay;
            DateTime start = Convert.ToDateTime(pausebeginn);
            TimeSpan zwischen = (DateTime.Now - Convert.ToDateTime(start)).Add(pause);


            label1.Text = zwischen.ToString();

            conn.Close();
        }

When the code is executed it tells me:执行代码时,它告诉我:

TimeSpan pause = Convert.ToDateTime(pausenzeit).TimeOfDay;

The charters are not detected as a valid DateTime value (Die Zeichenfolge wurde nicht als gültiges DateTime erkannt)章程未被检测为有效的DateTime时间值 (Die Zeichenfolge wurde nicht als gültiges DateTime erkannt)

Format:格式:

 DB pstart = yyyy-MM-dd HH:mm:ss
 DB ptotal = HH:mm:ss

Does anyone see my mistake (besides not having the requests parameterized yet)?有没有人看到我的错误(除了没有参数化的请求)?

I agree with everyone else here that the best case scenario is that your dates should be stored as dates.I am going to make some assumptions.我同意这里的其他人的观点,最好的情况是您的日期应该存储为日期。我将做一些假设。 One that your database is out of your control or too time consuming/ not a priority to deal with for what ever reason.您的数据库超出您的控制或太耗时/不是优先处理的原因,无论出于何种原因。 So i will assume that makes your question how vest to parse your dates and time spans in those formats.所以我会假设这让你的问题是如何背心以这些格式解析你的日期和时间跨度。 Im also going to assume you deal with nulls and format exceptions for dodgy data separately.我还将假设您分别处理不可靠数据的空值和格式异常。

Personally i prefer to use the parse exact method on both the date time.就我个人而言,我更喜欢在日期时间上使用解析精确方法。 You can use it like so usng your formats above(replace the string dates with your variable as you see fit)您可以像使用上面的格式一样使用它(用您认为合适的变量替换字符串日期)

        CultureInfo provider = CultureInfo.InvariantCulture;
        DateTime thedate = DateTime.ParseExact("2019-10-21 22:05:23", "yyyy-MM-dd HH:mm:ss",provider);
        TimeSpan timeSpan = TimeSpan.ParseExact("14:04:41", @"h\:mm\:ss", provider);

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

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