DateTime设置了第二天的日期



我有一个Google API,该API需要日期和时间,并在客户日历中设置了一个事件,问题是我正在使用日期时间将小时添加到我启动时间为12pm的时间无论出于何种原因,中午,它将在我的Google日历中列出。

这是设置日期和时间的代码:

// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes  values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock 
if (ddAptAmPm.SelectedValue == "PM")
    iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";

int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);

任何人都可以看到我在哪里做错了

    if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock 
       iHour += 12;

应该是:

if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock 
    iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12) 
    iHour = 0;

因为12 12是24,而今天加24小时是第二天。

写它的另一种方法:

if (iHour == 12) // 12 is **before** 1
    iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock 
    iHour += 12;

您可以做的另一种方法是以特定格式(包括AM或PM指定)构造日期字符串,然后使用DateTime.ParseExact创建startDate。这样,您就不必进行所有从字符串到int的转换

例如,此代码将替换您当前拥有的所有内容和包括startDate分配:

// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text, 
    ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt", 
    CultureInfo.InvariantCulture);

您可以在此处阅读有关日期和时间格式字符串的更多信息。

相关内容

最新更新