Files
2025-08-11 10:43:19 +08:00

115 lines
3.3 KiB
Objective-C
Executable File

//
// NSString+Time.m
// SweetParty
//
// Created by bj_szd on 2022/7/4.
//
#import "NSString+Time.h"
@implementation NSString (Time)
+ (NSString *)compareCurrentTime:(NSString *)str
{
NSDate *timeDate;
if ([str containsString:@" "]) {
//把字符串转为NSdate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
timeDate = [dateFormatter dateFromString:str];
}else {
timeDate = [NSDate dateWithTimeIntervalSince1970:[str integerValue]];
}
//得到与当前时间差
NSTimeInterval timeInterval = [timeDate timeIntervalSinceNow];
timeInterval = -timeInterval;
//标准时间和北京时间差8个小时
// timeInterval = timeInterval - 86060;
long temp = 0;
NSString *result;
if (timeInterval < 60) {
result = [NSString stringWithFormat:@"刚刚"];
}
else if((temp = timeInterval/60) <60){
result = [NSString stringWithFormat:@"%ld分钟前",temp];
}
else if((temp = temp/60) <24){
result = [NSString stringWithFormat:@"%ld小时前",temp];
}
else if((temp = temp/24) <30){
result = [NSString stringWithFormat:@"%ld天前",temp];
}
else if((temp = temp/30) <12){
result = [NSString stringWithFormat:@"%ld月前",temp];
}
else{
temp = temp/12;
result = [NSString stringWithFormat:@"%ld年前",temp];
}
return result;
}
+ (NSString *)timestampToDateString:(NSString *)str {
NSString *day;
if ([str containsString:@" "]) {
day = str;
}else {
if (str.length == 13) {
str = [NSString stringWithFormat:@"%ld", [str integerValue]/1000];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *theday = [NSDate dateWithTimeIntervalSince1970:[str longLongValue]];
day = [dateFormatter stringFromDate:theday];
}
return day;
}
+ (NSString *)timestampToDay:(NSString *)str {
NSString *day;
if ([str containsString:@" "]) {
day = str;
}else {
if (str.length == 13) {
str = [NSString stringWithFormat:@"%ld", [str integerValue]/1000];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *theday = [NSDate dateWithTimeIntervalSince1970:[str longLongValue]];
day = [dateFormatter stringFromDate:theday];
}
return day;
}
+ (NSString *)timestampToMDHM:(NSString *)str {
NSString *day;
if ([str containsString:@" "]) {
day = str;
}else {
if (str.length == 13) {
str = [NSString stringWithFormat:@"%ld", [str integerValue]/1000];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd HH:mm"];
NSDate *theday = [NSDate dateWithTimeIntervalSince1970:[str longLongValue]];
day = [dateFormatter stringFromDate:theday];
}
return day;
}
//获取当前时间戳,毫秒
+ (NSString *)getNowTimeTimestamp3 {
NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
return timeSp;
}
@end