1. 程式人生 > >NSDate的處理:前一天、後一天等關於時區偏移的處理以及在資料庫中的使用

NSDate的處理:前一天、後一天等關於時區偏移的處理以及在資料庫中的使用

看來很多網上關於日期的處理,今天、昨天、前天、後天、一週等,滿心歡喜的拿著去驗證結果總是不盡如人意,看別別人的程式碼看的腦漲,自己就寫一個簡單的,自己來用,以後用其他的方法,我會在完善,再次記錄,以方便以後查閱

                                                                                                                                    --宋飛祥    2014.7.19

直接上程式碼,很容易理解:

#import <Foundation/Foundation.h>

@interface MyCutomNSDateDeal : NSObject

+(NSInteger)timeZoneOffset;
+(NSInteger)preDayOfTheDate_start:(NSDate *)date;
+(NSInteger)preDayOfTheDate_end:(NSDate *)date;
+(NSInteger)nextDayOfTheDate_start:(NSDate *)date;
+(NSInteger)nextDayOfTheDate_end:(NSDate *)date;

@end

#import "MyCutomNSDateDeal.h"

@implementation MyCutomNSDateDeal

+(NSInteger)timeZoneOffset
{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger offset = [zone secondsFromGMTForDate:date];
    return offset;
}
/**
 *  根據給出的日期,返回該日期的前一天的起點(相對於日期起點,seconds的計數)
 *
 *  @param date 日期
 *
 *  @return 返回的是seconds計數,相對於日曆系統起始至該日期前一天的起點(就是0點)
 */
+(NSInteger)preDayOfTheDate_start:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:date];
    [components setHour:-[components hour]-24];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    NSDate *date1 = [cal dateByAddingComponents:components toDate:date options:0];
    
    return [date1 timeIntervalSince1970]+[self timeZoneOffset];
}

/**
 *  根據給出的日期,返回該日期的前一天的終點(也就是給出日期的起點)
 *
 *  @param date 給定的日期
 *
 *  @return 返回的是seconds計數
 */
+(NSInteger)preDayOfTheDate_end:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:date];
    [components setHour:-[components hour]];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    NSDate *date1 = [cal dateByAddingComponents:components toDate:date options:0];
    
    return [date1 timeIntervalSince1970]+[self timeZoneOffset];
}

+(NSInteger)nextDayOfTheDate_start:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:date];
    [components setHour:-[components hour]+24];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    NSDate *date1 = [cal dateByAddingComponents:components toDate:date options:0];
    
    return [date1 timeIntervalSince1970]+[self timeZoneOffset];
    
}

+(NSInteger)nextDayOfTheDate_end:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:date];
    [components setHour:-[components hour]+ 2*24];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    NSDate *date1 = [cal dateByAddingComponents:components toDate:date options:0];
    
    return [date1 timeIntervalSince1970]+[self timeZoneOffset];
    
}

//+(NSInteger)preWeekOfTheDate_

@end


使用如下:

這裡我取得date 為當天的,使用者可以換成自己想要的相對日期即可!!

 NSDate *today = [NSDate date];
    NSLog(@"today ::::: %@",today);
    NSInteger today_int = [MyCutomNSDateDeal preDayOfTheDate_start:today];
    NSDate *per_start = [NSDate dateWithTimeIntervalSince1970:today_int];
    NSLog(@"per_start _:_ %@",per_start);
    NSDate *per_end = [NSDate dateWithTimeIntervalSince1970:[MyCutomNSDateDeal preDayOfTheDate_end:today]];
    NSLog(@"per_end -:- %@",per_end);
    NSDate *next_start = [NSDate dateWithTimeIntervalSince1970:[MyCutomNSDateDeal nextDayOfTheDate_start:today]];
    NSDate *next_end = [NSDate dateWithTimeIntervalSince1970:[MyCutomNSDateDeal nextDayOfTheDate_end:today]];
    NSLog(@"next_start === %@",next_start);
    NSLog(@"next_end === %@",next_end);
列印結果如下:
2014-07-19 <span style="color:#FF0000;">15:26:30.565 </span>FMDBSortByDateDemo[4423:60b] today ::::: 2014-07-19 <span style="color:#FF0000;">07:26:30</span> +0000
2014-07-19 15:26:30.566 FMDBSortByDateDemo[4423:60b] per_start _:_ 2014-07-18 00:00:00 +0000
2014-07-19 15:26:30.566 FMDBSortByDateDemo[4423:60b] per_end -:- 2014-07-19 00:00:00 +0000
2014-07-19 15:26:30.566 FMDBSortByDateDemo[4423:60b] next_start === 2014-07-20 00:00:00 +0000
2014-07-19 15:26:30.567 FMDBSortByDateDemo[4423:60b] next_end === 2014-07-21 00:00:00 +0000
第一行列印可以看出,我們列印的時間理我現在真正需要的時間差8個小時,這就是時區的偏移,加上8個小時就對了,下面的列印在我定義的標頭檔案中,已經把相對偏加上了!

這裡我想說的是:我專案中用到要存資料和date,而資料庫(FMDB)是不支援date格式的,我採取的是把相對日曆起點的seconds(秒)存起來,通過比對秒數來取想要的資料!

如果大家有好的方法,可以交流!!

下面是我的資料庫取值過程:

 NSInteger inter = [MyCutomNSDateDeal preDayOfTheDate_end:today];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Temperature WHERE Date > %i ",inter];
   // NSString *sql = [NSString stringWithFormat:@"SELECT * FROM Temperature WHERE Date between %li and %li",from,to];

    if ([db open]) {
       FMResultSet *rs = [db executeQuery:sql];
        while ([rs next]) {
            NSString *name = [rs stringForColumn:@"Name"];
            NSInteger time = [rs intForColumn:@"Date"];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
            float temp = [rs doubleForColumn:@"Temperature"];
            NSString *event = [rs stringForColumn:@"Event"];
            NSLog(@"Name:%@,Date:%@,Temperature:%f,Event:%@",name,date,temp,event);
        }
    }

兩個sql語句都驗證了,是正確的,有一點我要說的是,我們在處理取出的資料時,加上了偏移量,所以我們存取資料時,也要加上偏移量,應該如下:

-(void)temperatureAndDateUpdate:(float)value
{
    NSDate *date = [NSDate date];
    NSInteger time = [date timeIntervalSince1970];
    time = time + [MyCutomNSDateDeal timeZoneOffset]; //加上時區偏移量
    NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:time];
    NSLog(@"temperature update    date1 === %@",date1);
    if ([db open]) {
        
        [db executeUpdate:@"INSERT INTO Temperature(Name,Date,Temperature,Event) VALUES (?,?,?,?)",@"SFX",[NSNumber numberWithInteger:time],[NSNumber numberWithFloat:value],@"吃藥"];
        NSLog(@"success!!");
    }else
    {
       NSLog(@"error:   %@   %@",[db lastError],[db lastErrorMessage]);
    }
    [db close];
}