将NSDate转换为NSInteger,然后转换为NSString

LJ *_*son 1 vb6 objective-c ios

我试图复制当前在VB中实现的功能.我需要做的是将日期转换为长整数,然后将其转换为字符串.我还需要将一个长整数转换为该整数的HEX值,然后将其转换为字符串.

这是我在VB中使用的代码.

If dteCreated <> #12:00:00 AM# Then
strHash = CStr(CLng(dteCreated))

If InStr(1, strHash, ".", vbTextCompare) > 0 Then
    strHash = Left(strHash, InStr(1, strHash, ".", 1) - 1) & "_" & Mid(strHash, InStr(1, strHash, ".", 1) + 1)
Else
    strHash = strHash & "_00000"
End If

strHash = strHash & "_" & CStr(Hex(intereq))
Run Code Online (Sandbox Code Playgroud)

这两个变量是dteCreated(Date)和intereq(Long).这构建的是在我们的服务器上解码的散列查询字符串.

任何人都可以帮助我在Objective-C中使用的方法来获得相同的功能吗?

zap*_*aph 7

您可以使用自1970年以来的引用转换为NSTimeInterval,它是一个double,使用:

- (NSTimeInterval)timeIntervalSince1970
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds
Run Code Online (Sandbox Code Playgroud)

您可以将double转换为int并返回,而Cast只会丢失一秒的分数.

例:

NSDate *today = [NSDate date];
NSLog(@"today %@", today);

NSTimeInterval interval = [today timeIntervalSince1970];
NSString *hexInterval = [NSString stringWithFormat:@"%08x", (int)interval];
NSLog(@"hexInterval %@", hexInterval);

unsigned intInterval;
NSScanner *scanner = [NSScanner scannerWithString:hexInterval];
[scanner scanHexInt:&intInterval];

NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(@"date  %@", date);
Run Code Online (Sandbox Code Playgroud)

NSLog输出:

today 2011-11-15 18:34:07 +0000
hexInterval 4ec2acf0
date  2011-11-15 18:34:07 +0000
Run Code Online (Sandbox Code Playgroud)