在 Java 中将字符串转换为日历对象

发布于 2024-10-22 01:05:07 字数 302 浏览 17 评论 0 原文

我是 Java 新手,通常使用 PHP。

我正在尝试转换这个字符串:

2011 年 3 月 14 日星期一 16:02:37 GMT

放入日历对象中,以便我可以像这样轻松地提取年份和月份:

String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);

手动解析它是一个坏主意吗?使用子字符串方法?

任何建议都会有帮助谢谢!

I am new to Java, usually work with PHP.

I am trying to convert this string:

Mon Mar 14 16:02:37 GMT 2011

Into a Calendar Object so that I can easily pull the Year and Month like this:

String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);

Would it be a bad idea to parse it manually? Using a substring method?

Any advice would help thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

在梵高的星空下 2024-10-29 01:05:07
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done

注意:根据您的环境/要求设置Locale


另请参阅

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done

note: set Locale according to your environment/requirement


See Also

少女七分熟 2024-10-29 01:05:07

tl;dr

现代方法使用 java.time 类。

YearMonth.from(
    ZonedDateTime.parse( 
        "Mon Mar 14 16:02:37 GMT 2011" , 
        DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
     )
).toString()

2011年3月

避免遗留日期时间类

现代方法是使用 java.time 类。旧的日期时间类(例如Calendar)已被证明设计不佳、令人困惑且麻烦。

定义自定义格式化程序以匹配您的字符串输入。

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );

解析为 ZonedDateTime

ZonedDateTime zdt = ZonedDateTime.parse( input , f );

您对年份和月份感兴趣。 java.time 类包含用于此目的的 YearMonth 类。

YearMonth ym = YearMonth.from( zdt );

如果需要,您可以询问年份和月份数字。

int year = ym.getYear();
int month = ym.getMonthValue();

但是 toString 方法会生成标准 ISO 8601 格式的字符串。

String output = ym.toString();

把这一切放在一起。

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();

转储到控制台。

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );

输入:2011 年 3 月 14 日星期一 16:02:37 GMT

时间:2011-03-14T16:02:37Z[GMT]

年:2011-03

实时代码

请参阅此代码在 IdeOne.com 中运行

转换

如果您必须有一个Calendar对象,则可以转换为GregorianCalendar 使用添加到旧类的新方法。

GregorianCalendar gc = GregorianCalendar.from( zdt );

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date< /a>, <代码>日历,& SimpleDateFormat< /代码>

要了解更多信息,请参阅 Oracle 教程 。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 jeps/170" rel="noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。 Hibernate 5 和 Hibernate 5 JPA 2.2 支持 java.time。

从哪里获取 java.time 类?

tl;dr

The modern approach uses the java.time classes.

YearMonth.from(
    ZonedDateTime.parse( 
        "Mon Mar 14 16:02:37 GMT 2011" , 
        DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
     )
).toString()

2011-03

Avoid legacy date-time classes

The modern way is with java.time classes. The old date-time classes such as Calendar have proven to be poorly-designed, confusing, and troublesome.

Define a custom formatter to match your string input.

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );

Parse as a ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.parse( input , f );

You are interested in the year and month. The java.time classes include YearMonth class for that purpose.

YearMonth ym = YearMonth.from( zdt );

You can interrogate for the year and month numbers if needed.

int year = ym.getYear();
int month = ym.getMonthValue();

But the toString method generates a string in standard ISO 8601 format.

String output = ym.toString();

Put this all together.

String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );

input: Mon Mar 14 16:02:37 GMT 2011

zdt: 2011-03-14T16:02:37Z[GMT]

ym: 2011-03

Live code

See this code running in IdeOne.com.

Conversion

If you must have a Calendar object, you can convert to a GregorianCalendar using new methods added to the old classes.

GregorianCalendar gc = GregorianCalendar.from( zdt );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

献世佛 2024-10-29 01:05:07

好吧,我认为复制 SimpleDateFormat

另一方面,我个人建议如果可以的话完全避免CalendarDate,并使用Joda Time 相反,它是一个设计得更好的日期和时间 API。例如,您需要注意 SimpleDateFormat 不是线程安全的,因此每次使用它时您要么需要线程局部变量、同步,要么需要一个新实例。 Joda 解析器和格式化器是线程安全的。

Well, I think it would be a bad idea to replicate the code which is already present in classes like SimpleDateFormat.

On the other hand, personally I'd suggest avoiding Calendar and Date entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware that SimpleDateFormat is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.

网名女生简单气质 2024-10-29 01:05:07

不需要创建新的日历,SimpleDateFormat 已经在下面使用了日历。

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(我还不能发表评论,这就是我创建新答案的原因)

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

恏ㄋ傷疤忘ㄋ疼 2024-10-29 01:05:07

SimpleDateFormat 很棒,但请注意,在处理小时时,HHhh 不同。 HH 将返回基于 24 小时的时间,hh 将返回基于 12 小时的时间。

例如,以下将返回 12 小时时间:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

而这将返回 24 小时时间:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
何以畏孤独 2024-10-29 01:05:07

解析带有时区的时间,模式中的 Z 表示时区

String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(aTime));
    Log.i(TAG, "time = " + cal.getTimeInMillis()); 
} catch (ParseException e) {
    e.printStackTrace();
}

输出:它将返回 UTC 时间

1508899140000

在此处输入图像描述

如果我们不以 等模式设置时区yyyy-MM-dd'T'HH:mm:ssSimpleDateFormat 将使用在 Setting 中设置的时区

Parse a time with timezone, Z in pattern is for time zone

String aTime = "2017-10-25T11:39:00+09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(aTime));
    Log.i(TAG, "time = " + cal.getTimeInMillis()); 
} catch (ParseException e) {
    e.printStackTrace();
}

Output: it will return the UTC time

1508899140000

enter image description here

If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting

筱武穆 2024-10-29 01:05:07

是的,自己解析它是不好的做法。看一下SimpleDateFormat,就会变成将字符串转换为日期,您可以将日期设置为日历实例。

Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.

寒冷纷飞旳雪 2024-10-29 01:05:07

简单方法:

public Calendar stringToCalendar(String date, String pattern) throws ParseException {
    String DEFAULT_LOCALE_NAME = "pt";
    String DEFAULT_COUNTRY = "BR";
    Locale DEFAULT_LOCALE = new Locale(DEFAULT_LOCALE_NAME, DEFAULT_COUNTRY);
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    Date d = format.parse(date);
    Calendar c = getCalendar();
    c.setTime(d);
    return c;
}

Simple method:

public Calendar stringToCalendar(String date, String pattern) throws ParseException {
    String DEFAULT_LOCALE_NAME = "pt";
    String DEFAULT_COUNTRY = "BR";
    Locale DEFAULT_LOCALE = new Locale(DEFAULT_LOCALE_NAME, DEFAULT_COUNTRY);
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    Date d = format.parse(date);
    Calendar c = getCalendar();
    c.setTime(d);
    return c;
}
山色无中 2024-10-29 01:05:07

我认为这是有效的方法。

/**
 * Customized Date and Time Formats
 * Pattern                          Output
 * dd.MM.yy                         30.06.09
 * yyyy.MM.dd G 'at' hh:mm:ss z     2009.06.30 AD at 08:29:36 PDT
 * EEE, MMM d, ''yy Tue,            Jun 30, '09
 * h:mm a                           8:29 PM
 * H:mm                             8:29
 * H:mm:ss:SSS                      8:28:36:249
 * K:mm a,z                         8:29 AM,PDT
 * yyyy.MMMMM.dd GGG hh:mm aaa      2009.June.30 AD 08:29 AM
 */


public static LocalDateTime toLocalDateTime(long timeInMs){
    return Instant.ofEpochMilli(timeInMs).atZone(ZoneId.systemDefault()).toLocalDateTime();
}

public static LocalDateTime parseTimeNumeric(String time){
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("dd" + "." + "MM" + "." + "yy" + " " + "HH" + ":" + "mm" + ":" + "ss");
    try {
        calendar.setTime(formatter.parse(time));
    } catch (ParseException e) {
        return null;
    }
    return toLocalDateTime(calendar.getTimeInMillis());
}

例子

    LocalDateTime localDateTime = parseTimeNumeric("time format");

    localDateTime.getYear();
    localDateTime.getMonthValue();
    localDateTime.getDayOfMonth();
    localDateTime.getHour();
    localDateTime.getMinute();
    localDateTime.getSecond();

I think this is the efficient way.

/**
 * Customized Date and Time Formats
 * Pattern                          Output
 * dd.MM.yy                         30.06.09
 * yyyy.MM.dd G 'at' hh:mm:ss z     2009.06.30 AD at 08:29:36 PDT
 * EEE, MMM d, ''yy Tue,            Jun 30, '09
 * h:mm a                           8:29 PM
 * H:mm                             8:29
 * H:mm:ss:SSS                      8:28:36:249
 * K:mm a,z                         8:29 AM,PDT
 * yyyy.MMMMM.dd GGG hh:mm aaa      2009.June.30 AD 08:29 AM
 */


public static LocalDateTime toLocalDateTime(long timeInMs){
    return Instant.ofEpochMilli(timeInMs).atZone(ZoneId.systemDefault()).toLocalDateTime();
}

public static LocalDateTime parseTimeNumeric(String time){
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("dd" + "." + "MM" + "." + "yy" + " " + "HH" + ":" + "mm" + ":" + "ss");
    try {
        calendar.setTime(formatter.parse(time));
    } catch (ParseException e) {
        return null;
    }
    return toLocalDateTime(calendar.getTimeInMillis());
}

Example

    LocalDateTime localDateTime = parseTimeNumeric("time format");

    localDateTime.getYear();
    localDateTime.getMonthValue();
    localDateTime.getDayOfMonth();
    localDateTime.getHour();
    localDateTime.getMinute();
    localDateTime.getSecond();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文