IOS 关于日期和时间戳

什么是时间戳(百度百科)

时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

在开发中,我们常常需要获取系统当前时间,然后对时间进行操作,下面我介绍几种常见时间戳转换的方法。

常用转换

获取日期,将日期转换成字符串

  //获取当前日期
  NSDate *currentDate = [NSDate date]; 
  // 实例化日期格式
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  //设置日期格式
  [dateFormatter setDateFormat:@"YYYY-MM-dd"]; //YYYY表示年 MM表示月份 dd表示日 还有HH表示小时  mm表示分钟 ss表示秒,可以按照需求更改格式
  //将日期转换成字符串输出
  NSString *currentDateStr = [dateFormatter   stringFromDate:currentDate];

将日期字符串转换成日期

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 要转换的日期字符串 
NSString *dateString = @"2011-05-03 23:11:40";
// 设置为UTC时区// 这里如果不设置为UTC时区,会把要转换的时间字符串定为当前时区的时间(东八区)转换为UTC时区的时间 NSTimeZone *timezone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
 NSDate *someDay = [formatter dateFromString:dateString]; NSLog(@"%@", someDay);

时间格式

G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12,带前置0
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如2,无前置0
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
HH: 时,24小时制,带前置0
h: 时,12小时制,无前置0
hh: 时,12小时制,带前置0
m: 分,1-2位
mm: 分,2位,带前置0
s: 秒,1-2位
ss: 秒,2位,带前置0
S: 毫秒
Z: GMT(时区)

日期与时间戳转换

//时间戳转换成时间 
NSTimeInterval time =[timeString doubleValue]; 
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:time]; 
NSLog(@"date2 = %@",date2);
NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"yyyy/MM/dd"]; 
NSString *currentTime = [formatter stringFromDate:date2]; NSLog(@"当前时间:%@",currentTime);
//时间转时间戳 
NSString *timeStr = [NSString stringWithFormat:@"%.0f",[date2 timeIntervalSince1970]]; 
NSLog(@"时间戳:%@",timeStr);

将时间戳转换为星期几


- (NSString *)getWeekDayFordate:(long long)data
{
    //创建一个星期数组
    NSArray *weekday = [NSArray arrayWithObjects: [NSNull null], @"Sun", @"Mon", @"Tues", @"Wed", @"Thur", @"Fri", @"Sat", nil];
    //将时间戳转换成日期
    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:data];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:newDate];
    NSString *weekStr = [weekday objectAtIndex:components.weekday];
    return weekStr;
}

你可能感兴趣的:(IOS 关于日期和时间戳)