iOS 8 - get current date as DD/MM/YYYY
有人可以给我一些代码来获取日期吗?
1 2 3 4 5 6 7 | NSDateComponents *components = [[NSCalendarcurrentCalendar] component:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYearfromDate:[NSDatedate]]; NSString *day = [components day]; NSString *week = [components month]; NSString *year = [components year]; NSString *date = [NSString stringWithFormat:@"%@.%@.%@",day,week,year]; |
^^我的代码不起作用:S
有没有办法我可以在1周之内得到明天的日期,依此类推...
谢谢:)
您可以使用代码的变体,该变体使用
1 2 3 4 5 6 7 | NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]]; NSInteger day = [components day]; NSInteger month = [components month]; NSInteger year = [components year]; NSString *string = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)day, (long)month, (long)year]; |
请注意,这是
或者更好的是,您可以使用
1 2 3 | NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"d.M.yyyy"; NSString *string = [formatter stringFromDate:[NSDate date]]; |
1 2 3 4 5 | NSDate *todayDate = [NSDate date]; //Get todays date NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // here we create NSDateFormatter object for change the Format of date. [dateFormatter setDateFormat:@"dd-MM-yyyy"]; //Here we can set the format which we need NSString *convertedDateString = [dateFormatter stringFromDate:todayDate];// Here convert date in NSString NSLog("Today formatted date is %@",convertedDateString); |
你可以得到这样的
1 2 3 4 | let dateFormatter = DateFormatter() dateFormatter.dateFormat ="dd/MM/yyyy" let dateString = dateFormatter.string(from:Date()) print(dateString) |
尝试此操作,设置不同的组件单位:
1 2 3 4 5 6 7 8 | NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents * components = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:today]; NSInteger day = [components day]; NSInteger month = [components month]; NSInteger year = [components year]; |
如果您想获得其他日子,请使用此链接
日历获得另一天