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

Get current month date in date components

我正在像这样获取 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

如何正确获取月的值?

您需要先获取最后一个月的日期。

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)

如何创建初始 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
 */

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

您尝试设置结果组件的 timeZone 不会改变当前组件。如果您使用组件创建新的 NSDate.

,那只会影响组件的解释方式

假设您的目标是在 UTC 时间而不是本地时间获取 date 的组件,那么您需要在从 date 获取组件之前设置日历的 timeZone .

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 时间显示日期。