Trim NSDate to show date only

喜欢而已 提交于 2020-01-04 04:04:30

问题


I have been through all the similar questions, unfortunately non could solve my problem so I asked it. I need my function to return an NSDate and only date, but my return value contains timing as well, I have tried the setTimeStyle noStyle and every possible solution I could come up with, here is the code:

-(NSDate*)stringToDate{
    NSString *dateString = @"01-02-2010";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *date;
    date = [dateFormatter dateFromString:dateString];
    NSLog(@"%@",date);
    return date;
} 

The output is : 2010-01-31 16:00:00 +0000

What I want: 2010-01-31


回答1:


This can't work, when you print a NSDate object it will print the ENTIRE date. the way you get a string representation from a date is by using a NSDateFormatter

NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"dd-MM-yyyy";

NSLog(@"%@", [format stringFromDate:[NSDate new]]);

you can put this in a category on NSDate if you so desire.




回答2:


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];

NSLog(@"%@",theDate);



回答3:


NSDate is always a combination of date and time. You cant change the format of this. But if you want an output mentioned by you, you must convert it into NSString Just add the below code

NSLog(@"%@", [dateFormatter stringFromDate:date]);



回答4:


Grab a substring of the first 10 characters. Look at NSMakeRange and subStringWithRange.

NSString* dateOnlyAsString = [[[NSDate date] description] substringWithRange:NSMakeRange(0, 10)];

See the question How to get substring of NSString?.




回答5:


NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MM-yyyy"];
    NSDate *convertedDate = [df dateFromString:datestring1];
    NSLog(@"convertedDate....%@",convertedDate);
    [df setDateFormat:@"dd-MM-yyyy"];
    NSString     *date1= [df stringFromDate:convertedDate];



回答6:


    UIDatePicker *datepicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 250, 320, 60)];
    datepicker.datePickerMode = UIDatePickerModeDate;
    NSDate *date = datepicker.date;
    NSDate *date1 = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    // convert it to a string
    NSString *dateString = [dateFormat stringFromDate:date1];
    NSLog(@"date %@",dateString);
    datelabel.text =dateString;
    NSLog(@"text in the datelabel.text is %@",datelabel.text);

Try using by the following its works fine.if it not works let me know.



来源:https://stackoverflow.com/questions/19969741/trim-nsdate-to-show-date-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!