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

问题描述 投票:-2回答:2

我需要当前的日期字符串。我已经尝试过搜索了。我们目前得到的是什么

    [NSDate currentDate]; 

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

ios objective-c iphone nsdate nsdateformatter
2个回答
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];`

0
投票

如果有人在swift中寻找解决方案:

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:“IS”)“2019年4月14日上午12:11”

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

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

© www.soinside.com 2019 - 2024. All rights reserved.