使用joda-time转换时间字符串 [英] Convert Time-String using joda-time

查看:490
本文介绍了使用joda-time转换时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须遵循以下时间字符串:"23.02.2015 14:06:30 +01:00"我要打印.打印结果应为:"23.02.2015 15 :06:30". 经过一番研究,我发现了一个我认为不是一个好主意的解决方案.也许每个人都对如何正确执行此操作有一些结论?转换应使用joda-time完成. 预先感谢.

I have to following time-string: "23.02.2015 14:06:30 +01:00" which I want to print. The printed result should be: "23.02.2015 15:06:30". After some research I just found a solution which I dont think of to be a good idea. Perhabs anyone of you has some conclusions on how to do this right? The conversion should be done with joda-time. Thanks in advance.

**由于解释了上述重复项的差异而进行了更新: 我的第一种方法就像 Java所述:如何添加10我的时间中的分钟数来手动添加或删除小时数.我要强调的是,我不认为这是一个好主意,因为如果输入字符串将更改(可能出现错误的空间很大),这可能很危险.因此,我想知道joda-time是否具有某些功能,这些功能可以使我的生活更轻松,而到目前为止我还没有注意到.

** Update due to explaining difference for the mentioned dublicate: My first approach was just like mentioned in Java : how to add 10 mins in my Time to add or remove the hours manually. What I tried to underline is that I dont think of this as a good idea because this could be dangerous if the input string will change (much space for possible errors). So I was wondering if joda-time has some functionality that would make my life easier adn which I didnt notice so far.

推荐答案

您可以使用 DateTimeplusxx()方法;

You can use DateTime class plusxx() methods;

public static void main(String[] args) {
        String dateTime = "23.02.2015 14:06:30 +01:00";
        DateTimeFormatter dtf = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss Z");

        DateTime jodatime = dtf.parseDateTime(dateTime);
        DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
        System.out.println(dtfOut.print(jodatime));


        DateTime resultDateTime = jodatime.plusHours(1);
        System.out.println(dtfOut.print(resultDateTime));
    }

输出是;

23.02.2015 08:36:30
23.02.2015 09:36:30

结果日期没有错,有关此主题的更多信息,请查看这里.

Result date isn't wrong, for more information about this subject please look here.

对于固定日期,我在withZone( DateTimeZone.forID( "Europe/Prague" )处添加了时区;

For fixed dates, I added time zone with withZone( DateTimeZone.forID( "Europe/Prague" ) ;

public static void main(String[] args) {
        String dateTime = "23.02.2015 14:06:30 +01:00";
        DateTimeFormatter dtf = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss Z");

        DateTime jodatime = dtf.withZone( DateTimeZone.forID( "Europe/Prague" ) ).parseDateTime(dateTime);
        DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
        System.out.println(dtfOut.withZone( DateTimeZone.forID( "Europe/Prague" ) ).print(jodatime));


        DateTime resultDateTime = jodatime.plusHours(1);
        System.out.println(dtfOut.withZone( DateTimeZone.forID( "Europe/Prague" ) ).print(resultDateTime));
    }

输出为;

23.02.2015 14:06:30
23.02.2015 15:06:30

这篇关于使用joda-time转换时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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