【问题标题】:How to send NSDate with a certain date format as NSNumber? i.e convert NSDate to NSDate with another format?如何发送具有特定日期格式的 NSDate 作为 NSNumber?即用另一种格式将 NSDate 转换为 NSDate?
【发布时间】:2016-12-22 06:52:46
【问题描述】:

我有两个用户选择的日期:startDate 和 endDate。它们是 NSDate 实例,我必须将它们作为NSNumbers 的参数发送。如何在几秒钟内将它们转换为 NSNumber?

【问题讨论】:

  • 你的意思是NStimeInterval?然后从那里你可以格式化日期
  • 你不应该发送原始日期,因为你会遇到不同时区的问题。

标签: objective-c nsdate nsnumber


【解决方案1】:

使用下面的代码:

 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
// set format however you want
[formatter setDateFormat:@"ddMMyyyy"];
NSDate *date = [NSDate date];
NSString *string = [formatter stringFromDate:date];
NSNumber *num1 = @([string intValue]);
NSLog(@"%@",num1);

【讨论】:

  • 我试过了。它将日期作为 @"22/01/2016" 形式的字符串,但是当作为 int 时,只有 22 (int)。
  • ' NSDateFormatter *formatter = [[NSDateFormatter alloc]init];日期格式 =SHORT_DATE_FORMAT; [格式化程序 setDateFormat:dateFormat]; self.stringfr = [格式化字符串从日期:日期]; self.startDate = @([self.stringfr intValue]);'
  • 希望我的回答如你所愿。
  • 是的,完全正确。字符串中只有 22 个 @"22/01/2016"。
  • 让我检查一次
【解决方案2】:

1) 首先,获取MM/dd/yyyy格式的日期:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];

2) 获取字符串日期并从中删除“/”:

NString *string = [formatter stringFromDate:date];
NString *finalStr = [string stringByReplacingOccurrencesOfString:@"/" withString:@""];

3) 使用NSNumberFormatterNSString 转换为NSNumber

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString: finalStr];

希望,这就是你想要的!

【讨论】:

    【解决方案3】:

    如果您的意思是时间戳格式 NSDate *date = [NSDate 日期]; NSTimeInterval ti = [日期 timeIntervalSince1970]; How to convert NSDate into Unix timestamp in Objective C/iPhone?

    谢谢,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-15
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2015-06-06
      • 2012-03-31
      • 1970-01-01
      相关资源
      最近更新 更多