当我们将NSDate转换为NSDate组件时,NSDateComponents值是错误的

时间:2017-10-24 09:23:54

标签: ios xamarin xamarin.ios

我在将NsDate转换为特定时区(法国时区)和特定月份日期(10月30日,31日)的NSDate组件时遇到了问题。我怀疑这个问题是由于白天节省时间而发生的。可以请建议我如何克服这个问题。 请在下面找到我的代码段,

public static NSDate GetDate(int year, int month, int date, int hour, int mins, int secs)
        {
            NSCalendar calendar = NSCalendar.CurrentCalendar;
            NSDate today = new NSDate();
            // Get the year, month, day from the date
            NSDateComponents startDateComponents = calendar.Components(
            NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today);
            // Set the hour, minute, second
            startDateComponents.Year = year;
            startDateComponents.Month = month;
            startDateComponents.Day = date;
            startDateComponents.Hour = hour;
            startDateComponents.Minute = mins;
            startDateComponents.Second = secs;
            return calendar.DateFromComponents(startDateComponents);
        }

NSDate date = GetDate(2017, 10, 30, 6, 0, 0);
NSDateComponents dateComp= NSCalendar.CurrentCalendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour ,date);

除了10月30日,除了10月30日之外,我得到了错误的dateComponents值。你能否建议我错过任何转换日期的事情。

2 个答案:

答案 0 :(得分:0)

我想,可能你忘了设定timeZone。添加以下代码:

calendar.timeZone = YourTimeZone

答案 1 :(得分:0)

正如Son Thanh所说, timeZone 导致了这个问题。

但是,当我们设置不同的时区时,它仍然不起作用,我们必须手动添加GMT时间间隔。

尝试以下代码。

public static NSDate GetDate(int year, int month, int date, int hour, int mins, int secs)
{
    NSCalendar calendar = NSCalendar.CurrentCalendar;
    NSDate today = new NSDate();
    // Get the year, month, day from the date
    NSDateComponents startDateComponents = calendar.Components(
    NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today);
    // Set the hour, minute, second
    startDateComponents.Year = year;
    startDateComponents.Month = month;
    startDateComponents.Day = date;
    startDateComponents.Hour = hour;
    startDateComponents.Minute = mins;
    startDateComponents.Second = secs;

    NSDate d = calendar.DateFromComponents(startDateComponents);
    //interval between GMT and local timezone.
    nint interval = NSTimeZone.SystemTimeZone.SecondsFromGMT(d);
    //add the interval
    NSDate finalDate = d.AddSeconds(interval);
    return finalDate;
}