简体   繁体   中英

Convert NSDate to NSInteger and then to NSString

I am trying to duplicate the functionality that is currently implemented in 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.

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). 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?

You can use a reference since 1970 to convert to a NSTimeInterval which is a double, use:

- (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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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