简体   繁体   中英

To get time along with Date from DateTimePicker

我有一个格式很短的datetimepicker。我必须在后面的代码中获取时间和日期。现在12:00:0am插入日期和日期。相反,我需要插入当前时间以及从datetimepicker中选择的日期。任何人都可以救命?

Create a new DateTime using the date from your input and the time from DateTime.Now .

DateTime GetDateAndCurrentTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
}

The actual DateTime.Value from the picker is a full DateTime object with the current time.

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        DateTime dt = dateTimePicker1.Value;
        // or
        string s = string.Concat(dt.ToShortDateString(), DateTime.Now.ToShortTimeString());
    }

Full DateTime:

dateTimePicker1.Value;

'08/21/2011 14:42:11'

Short DateTime:

dateTimePicker1.Value.Date;

'08/21/2011 00:00:00'

The minimum value

'08/21/2011 00:00:00'

The maximum value

'08/21/2011 23:59:59'

Usage:

   var firstDate = dtpFrom.Value.Date; //  0:00:00
   var secondDate =  dtpTo.Value.Date.AddSeconds(86400 - 1); //23:59:59 - 86400 is 24 hours
   var list = Services.GetListForFilter(firstDate, secondDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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