IOS: Convert a NSDate object into a string to get the current time
This question already has an answer here:
You need to convert the date to a string and then add it to your output stream.
Use:
NSDate *currentTime = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"hh:mm:ss"];
NSString *timeString = [formatter stringFromDate:currentTime];
You can then send timeString in your output stream
Take a look at this, it has everything you need about date programming on iOS http://rypress.com/tutorials/objective-c/data-types/dates
Updated with some code samples:
Converting current time from NSDate to NSString:
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateFormat:@"M.d.y"];
NSString *stringResult = [dateFormatter stringFromDate:currentTime];
Setting Calendar
and TimeZone
is optional, but if could use them if needed. You also have different optionals for them, like NSCalendarIdentifierGregorian
, timeZoneForSecondsFromGMT:
, etc.
You have many options for dateFormat
, for example
M/d/y --> 11/4/2012
MM/dd/yy --> 11/04/12
MMM d, ''yy --> Nov 4, '12
h:mm a --> 8:09 PM
Alternatively, you can instead use dateStyle
and timeStyle
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
如果有人需要Swift中Assam + Adam的代码,这里是:
var currentTime:NSDate = NSDate.date()
var formatter:NSDateFormatter = NSDateFormatter.alloc().init()
formatter.setDateFormat("hh:mm:ss")
var timeString:NSString = formatter.stringFromDate(currentTime)
outputStream.write(timeString.UTF8String(),maxLength:timeString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
链接地址: http://www.djcxy.com/p/73988.html