【问题标题】:How to specify a time zone in UIDatePicker如何在 UIDatePicker 中指定时区
【发布时间】:2011-06-18 11:23:58
【问题描述】:
- (IBAction) buttonPressed {
NSDate *selected = [datePicker date];
NSString *message = [[NSString alloc] initWithFormat:@"The date and time you selected is: %@", selected];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected" message:message delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];

所以我的问题是下一个...如何在 Objective C 中使用 Datepicker 指定时区? 现在,如果我从 DatePicker 中选择一些值并按下显示警报的按钮 - 时间是错误的。这可能是因为时区不正确,但我不确定。那么任何想法都会很棒。在下图中,您可以看到我选择了 2:14 PM (14:14),但一个人说现在是 11:14,时区是 +000

更新 1 我已经对我的代码添加了一些更改,但仍然没有...

- (IBAction) buttonPressed {
NSDate *selected = [datePicker date];       
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
NSTimeZone *tz = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:tz];
NSString *formattedDate = [dateFormatter stringFromDate:selected];
NSString *message = [[NSString alloc] initWithFormat:@"The date and time you selected is: %@", formattedDate];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Date and Time Selected" 
                      message:message delegate:nil cancelButtonTitle:@"Yes, I did!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[dateFormatter release];

【问题讨论】:

    标签: iphone objective-c cocoa-touch datepicker


    【解决方案1】:

    在使用定义日期选择器的地方使用它

    datePicker.timeZone = [NSTimeZone localTimeZone];

    【讨论】:

      【解决方案2】:

      在 Swift 3 中:

      datePicker.timeZone = NSTimeZone.local
      

      【讨论】:

        【解决方案3】:

        您可以使用时区设置日期

        目标 C

        datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:10*60*60]; // Like GMT+10
        

        在 Swift 3 中:

        datePicker.timeZone = TimeZone(secondsFromGMT: 5*60*60)  // Like GMT+5
        

        【讨论】:

          【解决方案4】:

          您可以使用Australia/West (+08:00) , WST, Asia/Kolkata (+05:30)、IST 等时区字符串设置日期

          datePicker.timeZone = [NSTimeZone timeZoneWithName:@"timezone string goes here"] ;
          

          【讨论】:

            【解决方案5】:

            我认为这是因为选择了日期格式,请使用 NSDateFormatter 指定适当的日期格式并在您的字符串中使用它,这是一个链接Link

            【讨论】:

            • [dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm:ss"] - 这就是我所需要的!非常感谢丹尼尔
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-03-21
            • 1970-01-01
            • 2011-03-24
            • 2021-11-13
            • 2015-04-27
            • 1970-01-01
            • 2015-05-13
            相关资源
            最近更新 更多