iOS 8 – 获取当前date为DD / MM / YYYY
有人可以给我一些代码,我怎么得到的date?
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
有没有一种方法可以在一周内得到明天的date,等等…
谢谢 :)
您可以使用代码的变体,使用NSCalendar
和components
方法来检索数字组件:
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];
请注意,这是components
,而不是component
。
或者,更好的是,你可以使用NSDateFormatter
:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"dMyyyy"; NSString *string = [formatter stringFromDate:[NSDate date]];
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);
试试这个,设置不同的组件单元:
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];
如果你想得到其他的日子,使用这个链接日历得到其他的一天
你可以得到这样的
let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" let dateString = dateFormatter.string(from:Date()) print(dateString)