如何解析日期字符串的特定格式

时间:2015-07-20 18:34:56

标签: java string parsing

我有这些字符串

let guides = [UILayoutGuide(), UILayoutGuide(), UILayoutGuide()]
for guide in guides {
    self.view.addLayoutGuide(guide)
}
NSLayoutConstraint.activateConstraints([
    // guide heights are equal
    guides[1].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
    guides[2].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
    // guide widths are arbitrary, let's say 10
    guides[0].widthAnchor.constraintEqualToConstant(10),
    guides[1].widthAnchor.constraintEqualToConstant(10),
    guides[2].widthAnchor.constraintEqualToConstant(10),
    // guide left is arbitrary, let's say superview margin
    guides[0].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
    guides[1].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
    guides[2].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
    // bottom of each view is top of following guide
    views[0].bottomAnchor.constraintEqualToAnchor(guides[0].topAnchor),
    views[1].bottomAnchor.constraintEqualToAnchor(guides[1].topAnchor),
    views[2].bottomAnchor.constraintEqualToAnchor(guides[2].topAnchor),
    // top of each view is bottom of preceding guide
    views[1].topAnchor.constraintEqualToAnchor(guides[0].bottomAnchor),
    views[2].topAnchor.constraintEqualToAnchor(guides[1].bottomAnchor),
    views[3].topAnchor.constraintEqualToAnchor(guides[2].bottomAnchor)
])

String day1 = "June 3, 2015";

我想创建一种解析月,日和年的方法。目前我正在使用substring(),但认为可能有更好的解决方案?

4 个答案:

答案 0 :(得分:1)

使用SimpleDateFormat并从那里解析日期。

SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);

答案 1 :(得分:0)

请注意,这相当于MMMM dd, yyyy

试试这个。

SimpleDateFormat sdf = SimpleDateFormat("MMMM dd, yyyy");
Date parsed = sdf.parse(day1, new ParsePosition(0));
...

Ps:我没试过这段代码,请随时发表评论。

参考SimpleDateFormat

答案 2 :(得分:-1)

解决方案1:

使用StringTokenizer来标记字符串例如:

String str = "June 3, 2015";
StringTokenizer defaultTokenizer = new StringTokenizer(str);
while (defaultTokenizer.hasMoreTokens())
{
    System.out.println(defaultTokenizer.nextToken());
}

删除','从日期开始,即第二个令牌使用deletecharAt(int index);

希望对你有用

解决方案2: 使用split()方法

for (String retval: Str.split(" ", 3)){
         System.out.println(retval);
}

split() takes two argument first it will take the token , and the limit is how many strings. still you have to remove ',' .

还有另一个最简单的解决方案: 解决方案3:

SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);

答案 3 :(得分:-1)

你可以试试像

这样的东西
private static final String DAY = "dd";
private static final String MONTH = "MM";
private static final String YEAR = "yyyy";//use the format you want this just an example
Format month = new SimpleDateFormat(MONTH);
Format day = new SimpleDateFormat(DAY);
Format year = new SimpleDateFormat(YEAR);
month.format(your date); 
day.format(your date); 
year.format(your date);