如何以PST格式获取当前日期日期?

时间:2017-06-16 07:26:30

标签: ios objective-c iphone nsdate nsdateformatter

我需要当前的日期字符串。我已经尝试过搜索了。我们目前从

获得的
    [NSDate currentDate]; 

是UTC。要么告诉我如何在PST中转换它,要么直接在PST中获取当前日期。

2 个答案:

答案 0 :(得分:3)

NSDate *date = [NSDate date];

NSDateFormatter *formatterUTC = [[NSDateFormatter alloc] init];
formatterUTC.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatterUTC setDateFormat:@"MMM dd,yyyy, hh:mm a"];
NSString *dateString = [formatterUTC stringFromDate:date];

NSDate *dateFromString1 = [formatterUTC dateFromString:dateString];
NSDateFormatter *formatterPST = [[NSDateFormatter alloc] init];
[formatterPST setDateFormat:@"MMM dd,yyyy, hh:mm a"];

formatterPST.timeZone = [NSTimeZone timeZoneWithName:@"America/Los_Angeles"];

NSString *urdate = [formatterPST stringFromDate:dateFromString1];`

答案 1 :(得分:0)

万一有人在迅速寻找解决方案:

public func getCurrentDateIn(timeZone: String) -> Date? {

// get a dateFormatter
let dateFormatter              = DateFormatter()
dateFormatter.dateFormat       = "MMM dd,yyyy, hh:mm a"
let currentDateString : String = dateFormatter.string(from: Date())

// get currentDate in string format
guard let currentDate          = dateFormatter.date(from: currentDateString) else { return nil }

// change the timezone of dateFormatter to timeZone
dateFormatter.timeZone         = TimeZone.init(abbreviation: timeZone)

// get current date in timeZone in string format from dateFormatter
let timeZoneDateString         = dateFormatter.string(from: currentDate)

// change the timeZone of dateFormatter to current otherwise it will apply conversion again.
dateFormatter.timeZone         = TimeZone.current
return dateFormatter.date(from: timeZoneDateString)

}

//测试用例

getCurrentDateIn(timeZone:“ IST”) “ 2019年4月14日,上午12:11”

getCurrentDateIn(timeZone:“ PST”) “ 2019年4月13日,上午11:41”

getCurrentDateIn(timeZone:“ SGT”) “ 2019年4月14日,凌晨2:41”