iOS gets the current time and converts it to a timestamp

Source: Internet
Author: User
Tags current time
1. Get Current time
+ (NSString *) getcurrentdate
{
Get current time
NSDate *now = [NSDate Date];
Kelog (@ "Now date are:%@", now);

Nscalendar *calendar = [Nscalendar Currentcalendar];
Nsuinteger unitflags = Nsyearcalendarunit | Nsmonthcalendarunit | Nsdaycalendarunit | Nshourcalendarunit | Nsminutecalendarunit | Nssecondcalendarunit;
nsdatecomponents *datecomponent = [Calendar components:unitflags Fromdate:now];

Nsinteger year = [datecomponent year];
Nsinteger month = [datecomponent month];
Nsinteger day = [Datecomponent day];
Nsinteger hour = [Datecomponent hour];
Nsinteger minute = [datecomponent minute];
Nsinteger second = [datecomponent second];
NSString * currentdate = [NSString stringwithformat:@ "%ld-%.2ld-%.2ld%.2ld:%.2ld:%.2ld", Year,month,day,hour,minute, Second];

return currentdate;

}

2.NSDate converted to time stamp

NSDate *datenow = [NSDate date];//now time, you can output to see what format

NSString *timesp = [nsstring stringwithformat:@ '%d ', (long) [Datenow timeIntervalSince1970]];

NSLog (@ "timesp:%@", TIMESP); A method of time stamp value timestamp turning time


NSString Turn NSDate
+ (NSDate *) datewithstring: (NSString *) datastring
{
NSDateFormatter * format = [[NSDateFormatter alloc] init];

[Format setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];

NSDate * date = [format datefromstring:[self getcurrentdate]];

return date;
}



NSDate Turn NSString
+ (NSString *) Stringwithdate: (NSDate *) date{

NSDateFormatter * Dateformatter = [[NSDateFormatter alloc] init];

[Dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];

Nsstring*strdate = [dateformatter stringfromdate:[nsdate Date]];

NSLog (@ "%@", strdate);

[Dateformatter release];

return strdate;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.