簡體   English   中英

在日期組件中獲取當前月份日期

[英]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];

當我打印component的值時,我得到了這個值。

    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

如何正確獲取月份的值?

當您使用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 NSLog(@"Date: %@", date); 該日志以UTC時間顯示日期。

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

您需要首先獲取上個月的日期。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM