Time and time stamp use

Source: Internet
Author: User

First, get the current time
//获取当前时间- (NSString *)currentDateStr{    NSDate *currentDate = [NSDate date];//获取当前时间,日期    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//设定时间格式,这里可以设置成自己需要的格式    NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串    return dateString;}
Second, get the current timestamp
//获取当前时间戳- (NSString *)currentTimeStr{    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];    return timeString;}
Three, time stamp turn time
// 时间戳转时间,时间戳为13位是精确到毫秒的,10位精确到秒- (NSString *)getDateStringWithTimeStr:(NSString *)str{    NSTimeInterval time=[str doubleValue]/1000;//传入的时间戳str如果是精确到毫秒的记得要/1000    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象    //设定时间格式,这里可以设置成自己需要的格式        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];    return currentDateStr;}
Four, string to timestamp
//字符串转时间戳- (NSString *)getTimeStrWithString:(NSString *)str{    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000    return timeStr;}

Time and time stamp use

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.