【问题标题】:How to get Current Date date in PST format?如何以 PST 格式获取当前日期?
【发布时间】:2017-11-18 21:06:57
【问题描述】:

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

得到什么
    [NSDate currentDate]; 

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

【问题讨论】:

  • currentDate 不是 UTC,它是一个时间点,它没有时区。

标签: ios objective-c iphone nsdate nsdateformatter


【解决方案1】:
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];`

【讨论】:

  • 我不明白解释。在哪里转换为 UTC?
【解决方案2】:

如果有人在 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: "IST") “2019 年 4 月 14 日上午 12:11”

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

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

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 2020-10-16
    • 2012-11-12
    • 2015-04-04
    • 2013-10-04
    • 2011-12-06
    • 2014-08-12
    • 2011-07-09
    相关资源
    最近更新 更多