简体   繁体   中英

How can I set a DatePicker's date to yesterday?

This:

dtpFrom.DisplayDate = DateTime.Now -1;

(which is how it was done in Delphi), does not work; I get, "Operator '-' cannot be applied to operands of type 'System.DateTime' and 'int'"

Update: OK, I see I can do this, although I don't know if this is the most succinct way:

    int dtYear = DateTime.Now.Year;
    int dtMonth = DateTime.Now.Month;
    int dtDay = DateTime.Now.Day;

    dtpFrom.SelectedDate = new DateTime(dtYear, dtMonth, dtDay - 1);

...and now I see there is a better way, but must wait a minute before selecting a correct answer.

dtpFrom.DisplayDate = DateTime.Today.AddDays(-1);
dtpFrom.DisplayDate = DateTime.Now.AddDays(-1);

If anyone comes here and wanted to make the text to show yesterday default use

DatePickerName**.SelectedDate = DateTime.Today.AddDays(-1);**

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