有人可以给我一些代码我如何得到约会?
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
有没有办法可以在一周内获得明天的日期等等......
谢谢:)
答案 0 :(得分:22)
您可以使用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 = @"d.M.yyyy";
NSString *string = [formatter stringFromDate:[NSDate date]];
答案 1 :(得分:11)
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);
答案 2 :(得分:1)
你可以这样做
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)
答案 3 :(得分:0)
试试这个,设置不同的组件单元:
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];
如果您想获得其他日子,请使用此链接 calendar get other day