简体   繁体   English

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

[英]Convert NSDate to NSInteger and then to NSString

I am trying to duplicate the functionality that is currently implemented in VB. 我正在尝试复制VB中当前实现的功能。 What I need to do is convert a date to a long integer and then convert that to a string. 我需要做的是将日期转换为长整数,然后将其转换为字符串。 I also need to convert a long integer into a HEX value of that integer and then that to a string. 我还需要将一个长整数转换为该整数的十六进制值,然后再转换为字符串。

Here is the code I am using in VB. 这是我在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))

The two variables are dteCreated (Date) and intereq (Long). 这两个变量是dteCreated(日期)和intereq(长整数)。 What this builds is a hashed query string that is decoded on our server. 这构建了一个哈希查询字符串,该字符串在我们的服务器上解码。

Can anyone help with the methods I would need to use in Objective-C to get this same functionality? 谁能提供我需要在Objective-C中获得相同功能的方法的帮助?

You can use a reference since 1970 to convert to a NSTimeInterval which is a double, use: 您可以使用自1970年以来的引用将其转换为两倍的NSTimeInterval,请使用:

- (NSTimeInterval)timeIntervalSince1970
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds

You can convert the double to an int and back with casting loosing only the fractions of a second. 您可以将double转换为int,然后通过强制转换仅损失几分之一秒来转换。

Example: 例:

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);

NSLog output: NSLog输出:

today 2011-11-15 18:34:07 +0000
hexInterval 4ec2acf0
date  2011-11-15 18:34:07 +0000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM