在Google Tasks API中使用Joda-Time库将字符串转换为DateTime格式 [英] Using Joda-Time Library to Convert String to DateTime Format in Google Tasks API

查看:101
本文介绍了在Google Tasks API中使用Joda-Time库将字符串转换为DateTime格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期/时间字符串,需要将其发送到Google Tasks API,但我不知道如何转换 Joda-Time DateTime 对象转换为Java DateTime对象。我正在使用Android作为平台。



该字符串以 2012/07/19 22:00:00开头,并首先转换为Iso格式。 / p>

这是我的代码:

  Task task = new Task() ; 
task.setTitle(title);
task.setNotes(note);
DateTimeFormatter formatter = DateTimeFormat.forPattern( yyyy / MM / dd HH:mm:ss);
DateTime dt = formatter.parseDateTime(dateToIso( 2012/07/19 22:00:00));
task.setDue(dt);

私有String dateToIso(String date){
date = date.replace( /,-);
date = replaceCharAt(date,10,'T');
日期=日期+ .000Z;
返回日期;
}

我得到的错误是:


类型不匹配:无法从org.joda.time.DateTime转换为
com.google.api.client.util.DateTime


请协助。有关ISO转换的信息也将很有用。

解决方案

让Formatter解析字符串



问题是您的 dateToIso方法。没必要。 DateTimeFormatter 对象的工作是解析字符串给出正确的格式时。您确实确实给了它正确的格式。然后,您将字符串变形为另一种格式!



解决方案:(a)杀死dateToIso方法。 (b)删除对该方法的调用。只需将原始字符串传递给 parseDateTime



侧问题:您忽略了时区问题。因此,在解析该字符串时,Joda-Time将假定该日期时间的事件发生在JVM的默认时区中。因此,使用相同的输入但在另一台具有不同时区设置的计算机/ JVM上运行相同的代码将导致不同的输出。可能不是您想要的。经验教训:始终指定时区而不是依赖默认值。



另一个问题:您引用的错误是一个不同的问题,从Joda-Time转换为Google时间。继续阅读。



阅读文档



如果您要转换 org .joda.time.DateTime 对象到 com.google.api.client.util.DateTime 对象,只需查看 JavaDoc 。在那里,您将看到Google DateTime的构造函数带有一个java.util.Date。 Joda-Time具有内置的 toDate 方法,可转换为java.util.Date对象以实现与其他类的互操作性。



食物链



创建这样的对象食物链:


org.joda.time.DateTime→java.util.Date→com.google.api.client.util.DateTime


一些未经测试的代码…

  org.joda.time.DateTimeZone = org.joda.time.DateTimeZone.forID(非洲/约翰内斯堡); 
org.joda.time.DateTime jodaDateTime = new DateTime(timeZone);

//从Joda-Time转换为旧的捆绑j.u.Date
java.util.Date juDate = jodaDateTime.toDate();

//从j.u.Date转换为Google Date。
com.google.api.client.util.DateTime googleDateTime =新com.google.api.client.util.DateTime(juDate);



毫秒



或者,您可以提取并经过毫秒。



通常,我建议尽可能避免直接使用毫秒。使用毫秒可能会造成混乱,马虎且容易出错。毫秒计数很难调试,因为人类不能轻易理解 long 的日期时间含义。尽管Joda-Time和java.util.Date使用毫秒级(自Unix-epoch以来)作为其内部时间跟踪机制……





朝着另一个方向



[以下部分假定Google已用新的API取代了Question所引用的API。不确定此假设是否正确。]



com.google.gdata.data.DateTime 对象到Joda-Time DateTime,我将使用<$ c提供的毫秒计数$ c> getValue 方法。请注意,它返回的是64位的 long ,而不是32位的 int



确保将所需的时区分配给Joda-Time DateTime ,而不是隐式分配JVM的当前默认时区

  long millisecondsFromUnixEpoch = myGoogleDateTime.getValue(); 
org.joda.time.DateTimeZone区域= DateTimeZone.forID(非洲/约翰内斯堡);
org.joda.time.DateTime jodaDateTime = new DateTime(millisecondsFromUnixEpoch,zone);

Google API提供了其他一些选择。



toStringRfc822



您可以将 toStringRfc822 方法来生成要由Joda-Time解析的字符串。不幸的是,RFC 822难以解析且模棱两可。除其他故障外,它使用非标准的非唯一3-4字母时区代码,而不是使用正确的时区名称。由于其含糊不清,Joda-Time拒绝尝试解析这些代码。我认为Google在这里只包括它是为了与旧的API /库向后兼容。现代Internet协议已转移到ISO 8601。



toUiString



也许您可以调用 toUiString 方法来创建要由Joda-Time解析的字符串。不幸的是,他们的文档无法解释该方法使用哪种格式。



toString



您可以将 toString 方法,该方法记录为生成 xs:dateTime 字符串。该文档无法准确解释,但我猜它们是指 XML Schema规范中包含ISO 8601 。您可以尝试使用此方法查看它生成的内容。如果您想保留嵌入到Google对象中的UTC偏移量,则可能会很有用。但是请记住,时区不仅仅是UTC偏移量,因此您仍应将所需/期望的时区分配给Joda-Time DateTime对象。因此,我不确定这是否比将 long count-from-epoch传递给Joda-Time DateTime的构造方法更好。



java.time



现在 Java 8 发布了,也许Google可能对其API进行现代化升级以使用 java.time程序包



请注意,java.time扩展了ISO 8601格式以附加时区的正式名称,这是一个非常有用的想法。


I have a date/time string which needs to be sent to the Google Tasks API but I can't figure out how to convert a Joda-Time library DateTime object to a Java DateTime object. I'm using Android as the platform.

The string starts off as "2012/07/19 22:00:00" and is first converted to Iso format.

Here is my code:

    Task task = new Task();
    task.setTitle(title);
    task.setNotes(note);        
    DateTimeFormatter formatter =  DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
    DateTime dt = formatter.parseDateTime(dateToIso("2012/07/19 22:00:00"));
    task.setDue(dt);    

private String dateToIso(String date) {
    date = date.replace("/", "-");
    date = replaceCharAt(date, 10, 'T');
    date = date + ".000Z";
    return date;
}

The error I am getting is:

"Type mismatch: cannot convert from org.joda.time.DateTime to com.google.api.client.util.DateTime"

Please assist. Information with regards to ISO conversion would also be useful.

解决方案

Let Formatter Parse String

The problem is your "dateToIso" method. No need for that. The DateTimeFormatter object's job is to parse the string when given the correct format. You did indeed give it the correct format. And then you went and morphed the string into a different format!

Solution: (a) Kill your dateToIso method. (b) Delete the call to that method. Just pass the original string to parseDateTime.

Side-Problem: You ignored the issue of time zone. So when parsing that string, Joda-Time will assume the event of that date-time occurred in your JVM's default time zone. So running this same code with same inputs but on another computer/JVM with different time zone settings will result in different output. Probably not what you want. Lesson Learned: Always specify a time zone rather than rely on default.

Yet Another Problem: The error you quoted is a different problem, converting from Joda-Time to Google time. Read on.

Read The Doc

If you are trying to convert your org.joda.time.DateTime object to a com.google.api.client.util.DateTime object, just look at the JavaDoc. There you will see that the constructor of the Google DateTime takes a java.util.Date. Joda-Time has a built-in toDate method to convert to a java.util.Date object for interoperability with other classes.

Food-Chain

Create a food chain of objects like this:

org.joda.time.DateTime → java.util.Date → com.google.api.client.util.DateTime

Some untested code…

org.joda.time.DateTimeZone = org.joda.time.DateTimeZone.forID( "Africa/Johannesburg" );
org.joda.time.DateTime jodaDateTime = new DateTime( timeZone );

// Convert from Joda-Time to old bundled j.u.Date
java.util.Date juDate = jodaDateTime.toDate();

// Convert from j.u.Date to Google Date.
com.google.api.client.util.DateTime googleDateTime = new com.google.api.client.util.DateTime( juDate );

Milliseconds

Alternatively, you could extract and pass milliseconds.

Generally I recommend avoiding dealing directly with milliseconds where possible. Using milliseconds can be confusing, sloppy, and error-prone. A milliseconds count is difficult to debug as humans cannot readily decipher the date-time meaning of a long. While Joda-Time and java.util.Date use milliseconds-since-Unix-epoch as their internal time-tracking mechanism…

Going The Other Direction

[The following section assumes Google has supplanted the API referenced by the Question with a newer API. Not sure if this assumption is correct.]

When going from a com.google.gdata.data.DateTime object to a Joda-Time DateTime, I would use the milliseconds count-from-epoch provided by the getValue method. Note that it returns a 64-bit long, rather than a 32-bit int.

Be sure to assign the desired time zone to the Joda-Time DateTime rather than rely on implicitly assigning the JVM’s current default time zone.

long millisecondsFromUnixEpoch = myGoogleDateTime.getValue();
org.joda.time.DateTimeZone zone = DateTimeZone.forID( "Africa/Johannesburg" );
org.joda.time.DateTime jodaDateTime = new DateTime( millisecondsFromUnixEpoch, zone );

The Google API provides a few other choices.

toStringRfc822

You could call the toStringRfc822 method to generate a string to be parsed by Joda-Time. Unfortunately, RFC 822 is awkward and ambiguous to parse. Among other faults it uses the non-standard non-unique 3-4 letter time zone codes rather than proper time zone names. Joda-Time refuses to attempt parsing those codes because of their ambiguity. I assume Google only includes it here for backward-compatibility with old APIs/libraries. The modern Internet protocols have moved on to ISO 8601.

toUiString

Perhaps you could call the toUiString method to create a string to be parsed by Joda-Time. Unfortunately, their documentation fails to explain what format is used by that method.

toString

You could call the toString method that is documented as producing a xs:dateTime string. The doc fails to explain precisely, but I'm guessing they mean the XML Schema spec’s inclusion of ISO 8601. You might try this method to see what it generates. It may be useful if you want to preserve the offset-from-UTC embedded in the Google object. But remember that a time zone is more than an offset-from-UTC, so you should still assign the desired/expected time zone to your Joda-Time DateTime object. Therefore, I'm not sure if this better than just passing the long count-from-epoch to the constructor of Joda-Time DateTime.

java.time

Now that Java 8 is released, perhaps Google may modernize its APIs to use the java.time package.

Note that java.time extends the ISO 8601 format to append the formal name of the time zone, a very helpful idea.

这篇关于在Google Tasks API中使用Joda-Time库将字符串转换为DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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