• iOS开发时间戳与时间,时区的转换,汉字与UTF8,16进制的转换


    最近在调用聚合数据的时候遇到的时间戳等问题,现在做此笔记来记录一下。

    //获取当前系统的时间戳
    +(long)getTimeSp{
        long time;
        NSDate *fromdate=[NSDate date];
        time=(long)[fromdate timeIntervalSince1970];
        return time;
    }

    //将时间戳转换成NSDate
    +(NSDate *)changeSpToTime:(NSString*)spString{
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[spString intValue]];
        return confromTimesp;
    }
    //将时间戳转换成NSDate,加上时区偏移
    +(NSDate*)zoneChange:(NSString*)spString{
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[spString intValue]];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate:confromTimesp];
        NSDate *localeDate = [confromTimesp  dateByAddingTimeInterval: interval];
        return localeDate;
    }
    //比较给定NSDate与当前时间的时间差,返回相差的秒数
    +(long)timeDifference:(NSDate *)date{
        NSDate *localeDate = [NSDate date];
        long difference =fabs([localeDate timeIntervalSinceDate:date]);
        return difference;
    }
    //将NSDate按yyyy-MM-dd HH:mm:ss格式时间输出
    +(NSString*)nsdateToString:(NSDate *)date{
        NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString* string=[dateFormat stringFromDate:date];
        return string;
    }
    //将yyyy-MM-dd HH:mm:ss格式时间转换成时间戳
    +(long)changeTimeToTimeSp:(NSString *)timeStr{
        long time;
        NSDateFormatter *format=[[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *fromdate=[format dateFromString:timeStr];
        time= (long)[fromdate timeIntervalSince1970];
        [format release];
        return time;
    }
    //获取当前系统的yyyy-MM-dd HH:mm:ss格式时间
    +(NSString *)getTime{
        NSDate *fromdate=[NSDate date];
        NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString* string=[dateFormat stringFromDate:fromdate];
        return string;
    }

    点击下载DEMOhttp://www.kuaipan.cn/file/id_30491149655345667.htm 访问密码:At7uJx
    //发送数据时,16进制数->Byte数组->NSData,加上校验码部分
    +(NSData *)hexToByteToNSData:(NSString *)str{
        int j=0;
        Byte bytes[[str length]/2];
        for(int i=0;i<[str length];i++)
        {
            int int_ch;  ///两位16进制数转化后的10进制数
            unichar hex_char1 = [str characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
            int int_ch1;
            if(hex_char1 >= '0' && hex_char1 <='9')
                int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
            else if(hex_char1 >= 'A' && hex_char1 <='F')
                int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
            else
                int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
            i++;
            unichar hex_char2 = [str characterAtIndex:i]; ///两位16进制数中的第二位(低位)
            int int_ch2;
            if(hex_char2 >= '0' && hex_char2 <='9')
                int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
            else if(hex_char2 >= 'A' && hex_char2 <='F')
                int_ch2 = hex_char2-55; //// A 的Ascll - 65
            else
                int_ch2 = hex_char2-87; //// a 的Ascll - 97
            int_ch = int_ch1+int_ch2;
            bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
    //        if (j==[str length]/2-2) {
    //            int k=2;
    //            int_ch=bytes[0]^bytes[1];
    //            while (k
    //                int_ch=int_ch^bytes[k];
    //                k++;
    //            }
    //            bytes[j] = int_ch;
    //        }
            j++;
        }
        NSData *newData = [[NSData alloc] initWithBytes:bytes length:[str length]/2 ];
        NSLog(@"%@",newData);
        return newData;
    }
    //接收数据时,NSData->Byte数组->16进制数
    +(NSString *)NSDataToByteTohex:(NSData *)data{
        Byte *bytes = (Byte *)[data bytes];
        NSString *hexStr=@"";
        for(int i=0;i<[data length];i++)
        {
            NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
            if([newHexStr length]==1)
                hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
            else
                hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
        NSLog(@"hexStr:%@",hexStr);
        return hexStr;
    }
    //将汉字字符串转换成16进制字符串
    +(NSString *)chineseToHex:(NSString*)chineseStr{
        NSStringEncoding encodingGB18030= CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSData *responseData =[chineseStr dataUsingEncoding:encodingGB18030 ];
        NSString *string=[sendSocket NSDataToByteTohex:responseData];
        return string;
    }
    //将汉字字符串转换成UTF8字符串
    +(NSString *)chineseToUTf8Str:(NSString*)chineseStr{
        NSStringEncoding encodingUTF8 = NSUTF8StringEncoding;
        NSData *responseData2 =[chineseStr dataUsingEncoding:encodingUTF8 ];
        NSString *string=[sendSocket NSDataToByteTohex:responseData2];
        return string;
    }
    //将十六进制字符串转换成汉字
    +(NSString*)changeLanguage:(NSString*)chinese{
        NSString *strResult;
        NSLog(@"chinese:%@",chinese);
        if (chinese.length%2==0) {
            //第二次转换
            NSData *newData = [sendSocket hexToByteToNSData:chinese];
            unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            strResult = [[NSString alloc] initWithData:newData encoding:encode];
            NSLog(@"strResult:%@",strResult);
        }else{
            NSString *strResult = @"已假定是汉字的转换,所传字符串的长度必须是4的倍数!";
            NSLog(@"%@",strResult);
            return NULL;
        }
        return strResult;
    }
    /////////////GBK,汉字,GB2312,ASCII码,UTF8,UTF16
    //UTF8字符串转换成汉字
    +(NSString*)changeLanguageUTF8:(NSString*)chinese{
        NSString *strResult;
        NSData *data=[sendSocket hexToByteToNSData:chinese];
        strResult=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        return strResult;
    }
    //将十六进制数转换成十进制
    -(NSString *)ToHex:(int)tmpid
    {
        NSLog(@"tmpid:%d",tmpid);
        NSString *nLetterValue;
        NSString *str =@"";
        int ttmpig;
        for (int i = 0; i<9; i++) {
            ttmpig=tmpid;
            tmpid=tmpid/16;
            switch (ttmpig)
            {
                case 10:
                    nLetterValue =@"A";break;
                case 11:
                    nLetterValue =@"B";break;
                case 12:
                    nLetterValue =@"C";break;
                case 13:
                    nLetterValue =@"D";break;
                case 14:
                    nLetterValue =@"E";break;
                case 15:
                    nLetterValue =@"F";break;
                default:nLetterValue=[[NSString alloc]initWithFormat:@"%i",ttmpig];               
            }       
            str = [nLetterValue stringByAppendingString:str];
            NSLog(@"str:%@",str);
            if (tmpid == 0) {
                break;
            }       
        }
        return str;
    }
    //Unicode转化为汉字
    + (NSString *)replaceUnicode1:(NSString *)unicodeStr {
        NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\u"withString:@"\U"];
        NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"""withString:@"\""];
        NSString *tempStr3 = [[@"""stringByAppendingString:tempStr2]stringByAppendingString:@"""];
        NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
        NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];
        return [returnStr stringByReplacingOccurrencesOfString:@"\r\n"withString:@" "];
    }

    //iso8859-1 到 unicode编码转换

    + (NSString *)changeISO88591StringToUnicodeString:(NSString *)iso88591String

    {

        NSMutableString *srcString = [[[NSMutableString alloc]initWithString:iso88591String] autorelease];

        [srcString replaceOccurrencesOfString:@"&" withString:@"&" options:NSLiteralSearch range:NSMakeRange(0, [srcString length])];

        [srcString replaceOccurrencesOfString:@"&加行末位两个字符" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [srcString length])];//#x

        NSMutableString *desString = [[[NSMutableString alloc]init] autorelease];

        NSArray *arr = [srcString componentsSeparatedByString:@";"];

        for(int i=0;i<[arr count]-1;i++){

            NSString *v = [arr objectAtIndex:i];

            char *c = malloc(3);

            int value = [StringUtil changeHexStringToDecimal:v];//将二进制转化为十进制

            c[1] = value  &0x00FF;

            c[0] = value >>8 &0x00FF;

            c[2] = '';

            [desString appendString:[NSString stringWithCString:c encoding:NSUnicodeStringEncoding]];

            free(c);

        }

        return desString;

    }

    NSString转换成URL编码

    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

    还原:

    stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding

    //十六进制数转十进制数,因为苹果采用的是小端模式,取第一个字符是取最高位数,取最后一个字符是个位数。所以需要乘以16的tmpid.length-i-1次方

    -(int)TotexHex1:(NSString*)tmpid

    {    

        int int_ch1=0;

        for(int i=0;i

            unichar hex_char = [tmpid characterAtIndex:i];

            int int_ch;

            if(hex_char >= '0' && hex_char <='9')

                int_ch = (hex_char-48); //// 0 的Ascll - 48

            else if(hex_char >= 'A' && hex_char <='F')

                int_ch = (hex_char-55); //// A 的Ascll - 65

            else

                int_ch = (hex_char-87); //// a 的Ascll - 97

            int_ch=int_ch*pow( 16, tmpid.length-i-1 );//pow的第二个参数根据小端模式或者大端模式调整,

            int_ch1 = int_ch1+int_ch;

            NSLog(@"%d",int_ch1);

        }

        return int_ch1;

    }

    - (UIImage*)imageRotatedByDegrees:(CGFloat)degrees

    {

    CGSize rotatedSize = self.size;

    if (isRetina) {

    rotatedSize.width *= 2;

    rotatedSize.height *= 2;

    }

    UIGraphicsBeginImageContext(rotatedSize);

    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    CGContextRotateCTM(bitmap, degrees * M_PI / 180);

    CGContextRotateCTM(bitmap, M_PI);

    CGContextScaleCTM(bitmap, -1.0, 1.0);

    CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

    }

    -(double)distanceBetweenOrderBy:(double)lat1 :(double)lat2 :(double)lng1 :(double)lng2{//lat纬度,lng进度

        CLLocationCoordinate2D coor;

        coor.latitude = lat2;

        coor.longitude = lng2;

        NSDictionary *tip =  BMKBaiduCoorForWgs84(coor);

        CLLocationCoordinate2D coor1=  BMKCoorDictionaryDecode(tip);

        CLLocation* curLocation1 = [[[CLLocation alloc] initWithLatitude:lat1longitude:lng1]autorelease];

        CLLocation* otherLocation = [[[CLLocation alloc] initWithLatitude:coor1.latitude longitude:coor1.longitude]autorelease];

        double distance  = [curLocation1 distanceFromLocation:otherLocation];

        return distance;

    }

    NSString *tempStr=[[NSString stringWithFormat:@"%@",[sendData subdataWithRange:NSMakeRange(0,1024)]] stringByReplacingOccurrencesOfString:@" " withString:@""] ;

     NSMutableString *myStr=[[NSMutableString alloc]init];

    for (int i=1; ilength-2; i=i+2) {

                    [myStr appendFormat:@"0x%@,",[tempStr substringWithRange:NSMakeRange(i, 2)]];

                }

  • 相关阅读:
    因打卡界面更新,稍修改主要代码【2021/1/16】
    Python爬虫:使用Selenium爬取指定上市公司(如浦发银行)的今年公告信息
    Python爬虫:爬取福州链家的不同区域的二手房成交信息
    蓝精灵小组第十三周学习总结
    2020-2021-1学期 20202417《网络空间安全专业导论》第十三周学习总结
    蓝精灵小组第十二周学习总结
    蓝精灵小组第十一周学习总结
    2020-2021-1学期 20202417《网络空间安全专业导论》第十二周学习总结
    2020-2021-1学期 20202417《网络空间安全专业导论》第十一周学习总结
    2020-2021-1学期 20202417《网络空间安全专业导论》第十周学习总结
  • 原文地址:https://www.cnblogs.com/liuyingjie/p/5208949.html
Copyright © 2020-2023  润新知