问题
Can anybody give me some code how I get the 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];
^^ my code is not working :S
And is there a way that I can get the date of tomorrow, in 1 week and so on...
Thanks :)
回答1:
You can either use a variation of your code that retrieves the numeric components using NSCalendar
with the components
method:
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];
Note, that's components
, not component
.
Or, better, you can use NSDateFormatter
:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"d.M.yyyy";
NSString *string = [formatter stringFromDate:[NSDate date]];
回答2:
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);
回答3:
You can get like this
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)
回答4:
try this ,set the different components unit:
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];
if your want to get other days ,use this link calendar get other day
来源:https://stackoverflow.com/questions/27790657/ios-8-get-current-date-as-dd-mm-yyyy