dateFromComponents提供错误的日期

时间:2016-08-06 13:57:43

标签: ios swift nsdate nsdatecomponents

我正在尝试从Date获取NSDateComponents个对象,但Calendar.date(from: Components)在我原始组件的日期前一天给出了一个日期。

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Year , .Month , .Weekday, .Day], fromDate: NSDate())
dateComponents.year = 2015
dateComponents.month = 9
dateComponents.day = 1
po calendar!.dateFromComponents(dateComponents)
▿ Optional(2015-08-31 18:30:00 +0000)
  - Some : 2015-08-31 18:30:00 +0000

2 个答案:

答案 0 :(得分:6)

calendar对象的时区设为UTC,并尝试从Date获取calendar

calendar.timeZone = NSTimeZone(name: "UTC")!

答案 1 :(得分:1)

它为您提供了var markers = []; var map; var labels = 'ABCD'; var labelIndex = 0; function addMarker(location) { var marker = new google.maps.Marker({ position: location, label: labels[labelIndex++ % labels.length], icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' map: map }); markers.push(marker);时区,只需通过像这样转换NSDateFormatter来转换日期,您就会得到答案 -

UTC

enter image description here