在日期组件中获取当前月份日期

时间:2018-07-06 09:35:39

标签: ios objective-c nsdate nsdateformatter nsdatecomponents

我正在获得日期为2018-06-01 00:00:00 +0000的NSDateComponents

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth|NSCalendarUnitYear |NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];
[components setTimeZone:[NSTimeZone timeZoneWithAbbreviation: @"UTC"]];
 NSInteger month =[components month];

当我打印components的值时,我得到了这个值。

    TimeZone: GMT (GMT) offset 0
    Calendar Year: 2018
    Month: 5
    Leap month: no
    Day: 31
    Hour: 21
    Minute: 0

我的预期结果应该是

    TimeZone: GMT (GMT) offset 0
    Calendar Year: 2018
    Month: 6
    Leap month: no
    Day: 1
    Hour: 0
    Minute: 0

如何正确获取月份的值?

3 个答案:

答案 0 :(得分:3)

使用NSCalendar components:fromDate:时,结果基于日历的当前时区,默认为用户的本地时区。

您尝试设置结果组件的timeZone不会更改当前组件。如果使用组件创建新的NSDate,那只会影响组件的解释方式。

假设您的目标是在UTC时间而不是本地时间获取date的组件,那么您需要先设置日历的timeZone,然后再从date获取组件。 / p>

NSDate *date = // your date
NSCalendar *calendar = NSCalendar.currentCalendar;
calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDateComponents *components = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];
NSLog(@"UTC Components: %@", components);

但是请记住,您必须了解您真正想要的时区。确保您确实想要UTC时区。不要仅仅因为它与NSLog(@"Date: %@", date);的输出匹配而使用UTC。该日志以UTC时间显示日期。

答案 1 :(得分:0)

如何创建初始的date对象?当我尝试该设置时,一切都会按预期进行:

NSString *dateString = @"2018-06-01 00:00:00 +0000";

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

NSDate *date = [dateFormatter dateFromString:dateString];
NSCalendar *calendar = NSCalendar.currentCalendar;
NSDateComponents *components = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:date];

NSLog(@"Before: %@", components);
/*
 Before: <NSDateComponents: 0x604000158e10>
 Calendar Year: 2018
 Month: 6
 Leap month: no
 Day: 1
 Hour: 2
 Minute: 0
 */

components.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSLog(@"After: %@", components);
/*
 After: <NSDateComponents: 0x604000158e10>
 TimeZone: GMT (GMT) offset 0
 Calendar Year: 2018
 Month: 6
 Leap month: no
 Day: 1
 Hour: 2
 Minute: 0
 */

答案 2 :(得分:-4)

您需要首先获取上个月的日期。

extension Date {

   //it will give the date of last month
   var previousMonthDate: Date {
      return Calendar.current.date(byAdding: .month, value: -1, to: self)!
   } 
}

从日期获取日期组成部分

let dt = Date()
let components = Calendar.current.dateComponents([.year, .month, .day], from: dt.previousMonthDate)
print(components.day ?? 0)
print(components.month ?? 0)
print(components.year ?? 0)