在Objective-C中检查日期格式 [英] Check date format in Objective-C

查看:58
本文介绍了在Objective-C中检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个包含日期的字符串.我想检查其格式是否为"dd/MM/yyyy".现在,我正在使用在同一页面中找到的代码:

I'm receiving a string containing a date. I want to check if it has the format "dd/MM/yyyy". Right now I'm using code that I found in this same page:

NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
    correctFormat = false;
}

在某些情况下它可以工作,但是例如,如果我输入"22-12-1996"而不是"22/12/1996",那么它将始终创建日期.还有另一种一致的方法吗?

It works for some cases, but for example, if I input "22-12-1996" instead of "22/12/1996", it creates the date anyway. Is there another way that's consistent?

推荐答案

NSDateFormatter 处理字符串日期的格式.

NSDateFormatter handle format of string dates.

NSDateFormatter的实例创建NSDate对象的字符串表示形式,并将日期和时间的文本表示形式转换为NSDate对象.

Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

尝试一下,看看:

// Set date format according to your string date format
// e.g.: For, 
// 22-12-1996 -> @"dd-MM-yyyy"
// 22/12/1996 -> @"dd/MM/yyyy"
// 1996-12-22 03:45:20 -> @"yyyy-MM-dd HH:mm:ss"

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy";
//dateFormatter.dateFormat = @"dd-MM-yyyy";

NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
    correctFormat = false;
}
NSLog("Date: %@",date);

注意:日期格式的每对字符都将相关的日期组件与日期实例相关联.您可以使用日期字符串模式创建任何类型的日期格式.

Note: Each pairs of characters in date format relates relevant date component with date instance. You can create any type of date format using date string pattern.

这是Apple提供的文档:日期格式器

Here is document by Apple: Date Formatters

  • 日期(天): dd
  • 月: MM或MMM或MMMM
  • 年份:yy或yyyy
  • Date (Day): dd
  • Month: MM or MMM or MMMM
  • Year: yy or yyyy

以下是日期格式列表:日期格式

Here is list of date formats: Date Formats

这篇关于在Objective-C中检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆