使用Java从String获取Month,Day和Year值 [英] Retrieve Month, Day and Year values from a String using Java

查看:532
本文介绍了使用Java从String获取Month,Day和Year值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从字符串中提取日,月和年值[如18/08/2012]。我尝试使用SimpleDateFormat,但它返回一个Date对象,我观察到所有的Get方法已被弃用。有没有更好的方法呢?

How to extract Day, Month and Year values from a string [like 18/08/2012]. I tried using SimpleDateFormat, but it returns a Date object and I observed that all the Get methods are deprecated. Is there any better way to do this?

谢谢

推荐答案

就个人而言,我会使用 Joda时间,使生活更加简单。特别是,这意味着您不需要担心日历的时区与 SimpleDateFormat - 您只需解析一下 LocalDate ,这就是数据真正显示的内容。这也意味着你不需要担心几个月是0的:)

Personally I'd use Joda Time, which makes life considerably simpler. In particular, it means you don't need to worry about the time zone of the Calendar vs the time zone of a SimpleDateFormat - you can just parse to a LocalDate, which is what the data really shows you. It also means you don't need to worry about months being 0-based :)

Joda时间使许多日期/时间操作更加愉快。

Joda Time makes many date/time operations much more pleasant.

import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;

public class Test {

    public static void main(String[] args) throws Exception {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy")
            .withLocale(Locale.UK);

        LocalDate date = formatter.parseLocalDate("18/08/2012");

        System.out.println(date.getYear());  // 2012
        System.out.println(date.getMonthOfYear()); // 8
        System.out.println(date.getDayOfMonth());   // 18
    }
}

这篇关于使用Java从String获取Month,Day和Year值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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