问题
I am developing news app and I have converted elapsed time from now to that date but when I run code I am getting following exception in my adapter class
java.time.format.DateTimeParseException: Text '09/10/2019' could not be parsed at index 0 could not be parsed, unparsed text found at index 19
below my Adapter class
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class TopHeadlinesAdapter(val context: Context) : RecyclerView.Adapter<TopHeadlinesAdapter.MyViewHolder>() {
var articleList : List<Article> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_list,parent,false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
return articleList.size
}
@SuppressLint("NewApi")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.articleTitle.text = articleList.get(position).title
holder.articleSourceName.text = articleList.get(position).source.name
Picasso.get().load(articleList.get(position).urlToImage).into(holder.image)
val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
val output = SimpleDateFormat("dd/MM/yyyy")
var d = Date()
try
{
d = input.parse(articleList[5].publishedAt)
}
catch (e: ParseException) {
e.printStackTrace()
}
val formatted = output.format(d)
val timelinePoint = LocalDateTime.parse(formatted)
val now = LocalDateTime.now()
var elapsedTime = Duration.between(timelinePoint, now)
println(timelinePoint)
println(now)
elapsedTime.toMinutes()
holder.articleTime.text = "${elapsedTime.toMinutes()}"
}
fun setMovieListItems(articleList: List<Article>){
this.articleList = articleList
notifyDataSetChanged()
}
@SuppressLint("NewApi")
fun example( ) {
}
class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
val image: ImageView = itemView!!.findViewById(R.id.imageView)
val articleTitle: TextView = itemView!!.findViewById(R.id.articleTitle)
val articleSourceName: TextView = itemView!!.findViewById(R.id.articleSourceName)
val imageCategory: ImageView = itemView!!.findViewById(R.id.imageCategory)
val articleTime: TextView = itemView!!.findViewById(R.id.articleTime)
}
}
Below is the JSON response:
> {
> "status": "ok",
> "totalResults": 38,
> "articles": [
> {
> "source": {
> "id": "cnn",
> "name": "CNN"
> },
> "author": null,
> "title": "The latest on the Trump impeachment inquiry: Live updates - CNN",
> "description": "The House is moving forward with its impeachment inquiry into President Donald Trump. Follow here for the
> latest.",
> "url": "https://www.cnn.com/politics/live-news/impeachment-inquiry-10-09-2019/index.html",
> "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/190830133142-trump-file-102019-super-tease.jpg",
> "publishedAt": "2019-10-09T09:02:00Z",
> "content": "Donald Trump drove Democrats to the first crucial pivot point of their impeachment confrontation on Tuesday with
> a defiant declaration that his administration would not cooperate with
> the investigation.\r\nIn a fierce counter-attack after days of failing
> to con… [+1326 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Kotaku.com"
> },
> "author": "Brian Ashcraft",
> "title": "Overwatch's Mei Is Becoming A Symbol Of The Hong Kong Resistance - Kotaku",
> "description": "After Chung “Blitzchung” Ng Wai called for the liberation of Hong Kong, Blizzard suspended the Hearthstone player
> and withheld any prize money. The decision has been widely criticized.
> Fans have now started posting images of Overwatch hero Mei supporting
> the …",
> "url": "https://kotaku.com/overwatchs-mei-is-becoming-a-symbol-of-the-hong-kong-re-1838899963",
> "urlToImage": "https://i.kinja-img.com/gawker-media/image/upload/s--p_VCwaM0--/c_fill,fl_progressive,g_center,h_900,q_80,w_1600/onlooi9lbhsfq73hv0m6.jpg",
> "publishedAt": "2019-10-09T09:00:00Z",
> "content": "After Chung Blitzchung Ng Wai called for the liberation of Hong Kong, Blizzard suspended the Hearthstone player and
> withheld any prize money. The decision has been widely criticized.
> Fans have now started posting images of Overwatch hero Mei supporting
> the Ho… [+493 chars]"
> },
> {
> "source": {
> "id": "the-new-york-times",
> "name": "The New York Times"
> },
> "author": null,
> "title": "California Power Outages: Fire Danger Prompts Utility to Cut Electricity - The New York Times",
> "description": "An intentional shut-off by Pacific Gas & Electric, the largest utility in the state, could affect as many as
> 800,000 customers.",
> "url": "https://www.nytimes.com/2019/10/09/us/pge-shut-off-power-outage.html",
> "urlToImage": "https://static01.nyt.com/images/2019/10/09/us/09blackout1/09blackout1-facebookJumbo.jpg",
> "publishedAt": "2019-10-09T07:00:00Z",
> "content": "Large swaths of central and Northern California were expected to be without electricity on Wednesday as the
> states largest utility planned to cut power as a safety precaution.
> The utility, Pacific Gas & Electric, said that around 800,000
> customers would b… [+833 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Bbc.com"
> },
> "author": "https://www.facebook.com/bbcnews",
> "title": "Johnson & Johnson ordered to pay man $8bn over breast growth - BBC News",
> "description": "A US jury finds Johnson & Johnson guilty of negligence over an anti-psychotic drug.",
> "url": "https://www.bbc.com/news/business-49982237",
> "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/C1BB/production/_109159594_gettyimages-1164571026.jpg",
> "publishedAt": "2019-10-09T06:33:31Z",
> "content": "Image copyrightGetty Images\r\nUS drug firm Johnson & Johnson has been told to pay $8bn (£6.6bn) in punitive
> damages to a man over claims he was not warned that an antipsychotic
> drug could lead to breast growth.\r\nA Philadelphia jury made the
> award to Nichol… [+1740 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Bbc.com"
> },
> "author": "https://www.facebook.com/bbcnews",
> "title": "Ecuador protesters storm parliament as unrest worsens - BBC News",
> "description": "President Lenín Moreno imposes a night curfew near government buildings in response to the unrest.",
> "url": "https://www.bbc.com/news/world-latin-america-49981521",
> "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/E14B/production/_109157675_057168834.jpg",
> "publishedAt": "2019-10-09T05:29:17Z",
> "content": "Image copyrightReutersImage caption\r\n Protesters who burst into the National Assembly building were driven
> out with tear gas\r\nPresident Lenín Moreno has imposed a night curfew
> near government buildings after protesters clashed with security
> forces inside Ecua… [+3234 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Nypost.com"
> },
> "author": "George A. King III",
> "title": "The next Yankees challenge will be so much harder - New York Post ",
> "description": "After the Yankees swept the feeble Twins out of the ALDS on Monday night in Minneapolis, Hal Steinbrenner said
> he and his family were very proud of his club. “But we are not there
> yet,’’ Steinbrenn…",
> "url": "https://nypost.com/2019/10/09/the-next-yankees-challenge-will-be-so-much-harder/",
> "urlToImage": "https://thenypost.files.wordpress.com/2019/10/a.j.-hinch-aaron-boone-kevin-cash.jpg?quality=90&strip=all&w=1200",
> "publishedAt": "2019-10-09T04:49:00Z",
> "content": "After the Yankees swept the feeble Twins out of the ALDS on Monday night in Minneapolis, Hal Steinbrenner said he
> and his family were very proud of his club.\r\nBut we are not there
> yet, Steinbrenner said. This is Step 1.\r\nStep 2 will be considerably
> harder to … [+3884 chars]"
> },
> {
> "source": {
> "id": "cnn",
> "name": "CNN"
> },
> "author": "Joshua Berlinger and Isaac Yee, CNN",
> "title": "Houston Rockets fan arrested in China after threatening to burn national flag - CNN",
> "description": "A 25-year-old Houston Rockets fan in China threatened to burn the Chinese flag in protest of the ongoing dispute
> between Beijing and the NBA team, and told police to \"come and arrest
> him.\"",
> "url": "https://www.cnn.com/2019/10/09/asia/houston-rockets-fan-arrested-china-intl-hnk-scli/index.html",
> "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/191009103249-china-jersey-fan-burning-flags-super-tease.jpg",
> "publishedAt": "2019-10-09T04:45:00Z",
> "content": null
> },
> {
> "source": {
> "id": null,
> "name": "Theathletic.com"
> },
> "author": "Jake Ciely",
> "title": "2019 Week 6 fantasy football rankings, sleepers, buy lows, sell highs - The Athletic",
> "description": "Jake Ciely presents his Week 6 fantasy football rankings with sleepers, buy lows, sell highs and more
> advice",
> "url": "https://theathletic.com/1278721/2019/10/09/2019-week-6-fantasy-football-rankings-sleepers-buy-lows-sell-highs/",
> "urlToImage": "https://cdn.theathletic.com/app/uploads/2019/07/18193559/USATSI_11443357-1024x683.jpg",
> "publishedAt": "2019-10-09T04:07:30Z",
> "content": "2019 Fantasy Football Week 6 Rankings and SleepersI don’t have any super-duper special fantasy advice this week.
> Well, I should say it’s not an overall strategy or deep insight intro
> this time, as it’s more just about a few league settings I believe
> everyone … [+647 chars]"
> },
> {
> "source": {
> "id": "cnn",
> "name": "CNN"
> },
> "author": "Jacqueline Howard, CNN",
> "title": "STDs on the rise: Cases of 3 common infections reach all-time highs in the US - msnNOW",
> "description": "Combined cases of gonorrhea, chlamydia and syphilis have risen to unprecedented numbers for the fifth consecutive
> year in the United States, according to a new STD report from the
> Centers for Disease Control and Prevention.",
> "url": "https://www.cnn.com/2019/10/08/health/std-cases-rising-us-study/index.html",
> "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/180221174110-03-couple-bed-sex-stock-super-tease.jpg",
> "publishedAt": "2019-10-09T04:00:00Z",
> "content": null
> },
> {
> "source": {
> "id": "cbs-news",
> "name": "CBS News"
> },
> "author": "Danielle Garrand",
> "title": "Saturn moons: 20 new moons discovered around Saturn — and scientists need help naming them - CBS News",
> "description": "The new discovery increases the moons orbiting the \"jewel of our solar system\" to 82, surpassing Jupiter",
> "url": "https://www.cbsnews.com/news/saturn-moons-20-new-moons-discovered-around-saturn-scientists-need-help-naming-them-2019-10-08/",
> "urlToImage": "https://cbsnews1.cbsistatic.com/hub/i/r/2019/10/09/5a296cfc-1e23-4bce-a83c-471557653aa2/thumbnail/1200x630g6/4a908aea749a2d9b60244c5d3e649e29/17848-pia12797-full.jpg",
> "publishedAt": "2019-10-09T03:25:00Z",
> "content": "Twenty new moons have been found to be orbiting Saturn — and scientists want the public's help in naming
> them, according to a Carnegie Institution for Science news release.
> The new discovery brings the total moons around the \"jewel of our
> solar system\" to 82.… [+2978 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Yahoo.com"
> },
> "author": null,
> "title": "Gwen Stefani and Blake Shelton are still fighting: 'I thought you loved me!' - Yahoo Movies",
> "description": "The Voice has fetishized extreme youth for the past few seasons — two of its most recent champion, Brynn Cartelli
> and Chevel Shepherd, were still in high school when they won — but
> Tuesday’s Blind Auditions episode was surprisingly bookended by
> stupendous, st…",
> "url": "https://www.yahoo.com/entertainment/gwen-stefani-blake-shelton-still-024712250.html",
> "urlToImage": "https://s.yimg.com/uu/api/res/1.2/7eqSuqOM2bqOfMJfMOSbnA--~B/aD0xMDgwO3c9MTkyMDtzbT0xO2FwcGlkPXl0YWNoeW9u/https://s.yimg.com/os/creatr-uploaded-images/2019-10/02294890-ea3f-11e9-bf57-9d7819cb6a82",
> "publishedAt": "2019-10-09T02:58:31Z",
> "content": "The Voice has fetishized extreme youth for the past few seasons two of its most recent champion, Brynn Cartelli and
> Chevel Shepherd, were still in high school when they won but Tuesdays
> Blind Auditions episode was surprisingly bookended by stupendous,
> standou… [+2042 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Vulture.com"
> },
> "author": "Charu Sinha",
> "title": "Drake Posts Instagram Story About His Father - Vulture",
> "description": "Gather around, Dennis Graham truthers.",
> "url": "http://www.vulture.com/2019/10/drake-posts-instagram-story-about-his-father.html",
> "urlToImage": "https://pixel.nymag.com/imgs/daily/vulture/2019/10/08/drakedad_8.w1200.h630.jpg",
> "publishedAt": "2019-10-09T02:04:00Z",
> "content": "Today in celebrities oversharing on social media about conflicts we had no idea were even happening, we have
> Drake telling the world via Instagram that his father will say
> anything to anyone thats willing to listen to him and revealing that
> its sad when famil… [+1388 chars]"
> },
> {
> "source": {
> "id": "usa-today",
> "name": "USA Today"
> },
> "author": "Sara MacNeil",
> "title": "‘A historic day’: Montgomery, Alabama, elects its first African-American mayor - USA TODAY",
> "description": "Steven Reed, the Montgomery County probate judge, beat TV station owner David Woods and will be sworn in as the
> city's first black mayor Nov. 12.",
> "url": "https://www.usatoday.com/story/news/nation/2019/10/08/montgomery-elects-steven-reed-its-first-african-american-mayor/3915021002/?utm_source=google&utm_medium=amp&utm_campaign=speakable",
> "urlToImage": "https://www.gannett-cdn.com/presto/2019/08/28/PMOY/d1c2e76b-7bfd-42ba-a572-e5e50ed24d3e-jc_electionnight_9.JPG?crop=2999,1687,x0,y0&width=3200&height=1680&fit=bounds",
> "publishedAt": "2019-10-09T01:50:00Z",
> "content": "Last SlideNext Slide\r\nMONTGOMERY, Ala. Montgomery, a city where more than half the population is black and
> known as the birthplace of the civil rights movement, elected an
> African American to the highest position in municipal government for
> the first time in … [+7031 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Slashgear.com"
> },
> "author": "JC Torres",
> "title": "Chuwi UBook Pro takes on the Microsoft Surface with few compromises - SlashGear",
> "description": "Although devices have existed long before, Microsoft has arguably made 2-in-1 computers more fashionable thanks
> to its Surface line. Even tablets like the Apple iPad Pro and the
> Samsung Galaxy Tab …",
> "url": "https://www.slashgear.com/chuwi-ubook-pro-takes-on-the-microsoft-surface-with-few-compromises-08594816/",
> "urlToImage": "https://scdn.slashgear.com/wp-content/uploads/2019/10/ubook-pro-1.jpg",
> "publishedAt": "2019-10-09T01:18:00Z",
> "content": "Although devices have existed long before, Microsoft has arguably made 2-in-1 computers more fashionable thanks
> to its Surface line. Even tablets like the Apple iPad Pro and the
> Samsung Galaxy Tab S have taken on that form factor to give them an
> air of produc… [+1927 chars]"
> },
> {
> "source": {
> "id": "nbc-news",
> "name": "NBC News"
> },
> "author": "Associated Press",
> "title": "Bernie Sanders' daughter-in-law dies of cancer at 46 - NBCNews.com",
> "description": "The daughter-in-law of Democratic presidential candidate Bernie Sanders has died, shortly after being
> diagnosed with cancer.",
> "url": "https://www.nbcnews.com/politics/2020-election/bernie-sanders-daughter-law-dies-cancer-46-n1064051",
> "urlToImage": "https://media3.s-nbcnews.com/j/newscms/2019_41/3044061/191008-bernie-sanders-campaign-ac-818p_b59f9fa6163cabb3f72eaf6290cdcb08.nbcnews-fp-1200-630.jpg",
> "publishedAt": "2019-10-09T01:05:00Z",
> "content": "The daughter-in-law of Democratic presidential candidate Bernie Sanders has died, shortly after being diagnosed with
> cancer. Rainè Riggs was 46.\r\nThe Lee & Martin Funeral Home in
> Burgettstown, Pennsylvania, says Riggs died Saturday, the day Sanders
> return… [+632 chars]"
> },
> {
> "source": {
> "id": "cnn",
> "name": "CNN"
> },
> "author": "Sandra Gonzalez, CNN",
> "title": "'Bachelor' star Peter Weber injured in 'freak accident' but doing OK - CNN",
> "description": "The star of the next edition of \"The Bachelor\" was involved in what the show's host Chris Harrison called
> a \"freak accident\" that left him needing stitches.",
> "url": "https://www.cnn.com/2019/10/08/entertainment/bachelor-peter-weber-accident/index.html",
> "urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/191008161026-peter-weber-super-tease.jpg",
> "publishedAt": "2019-10-09T00:57:00Z",
> "content": null
> },
> {
> "source": {
> "id": null,
> "name": "Wtop.com"
> },
> "author": "Dick Uliano",
> "title": "Time to get a flu shot: 11 cases reported in Maryland - WTOP",
> "description": "The Maryland Department of Health is already reporting 11 laboratory-confirmed cases since Sept. 1, and
> state health officials said the onset of flu only emphasizes the need
> for a flu shot.",
> "url": "http://wtop.com/health-fitness/2019/10/flu-is-here-no-putting-off-flu-shot/",
> "urlToImage": "https://wtop.com/wp-content/uploads/2018/06/Flu_Vaccine_85329.jpg",
> "publishedAt": "2019-10-09T00:56:15Z",
> "content": "Flu season has come early to Maryland.\r\nThe Maryland Department of Health is already reporting 11
> laboratory-confirmed cases since Sept. 1. State health officials said
> the onset of flu only emphasizes the need for a flu shot.\r\n“Get your
> flu shot now. Don’t pu… [+2725 chars]"
> },
> {
> "source": {
> "id": "the-hill",
> "name": "The Hill"
> },
> "author": "Aris Folley",
> "title": "California passes bill making HIV-prevention drugs available without prescription | TheHill - The Hill",
> "description": "California Gov. Gavin Newsom (D) has signed legislation into law that allows pharmacists in the s...",
> "url": "https://thehill.com/homenews/state-watch/464951-california-passes-bill-making-hiv-prevention-drugs-available-without",
> "urlToImage": "https://thehill.com/sites/default/files/newsomgavin_060518getty.jpg",
> "publishedAt": "2019-10-09T00:43:31Z",
> "content": "California Gov. Gavin NewsomGavin Christopher NewsomCalifornia creates first toll-free statewide mental health
> lineCalifornia inspires other states to push to pay college
> athletesEx-FCC counselor calls for federal consumer privacy lawMORE
> (D) has signed legis… [+1770 chars]"
> },
> {
> "source": {
> "id": null,
> "name": "Tweaktown.com"
> },
> "author": "Anthony Garreffa",
> "title": "Latest PlayStation 5 renders still have awesome V-shaped design - TweakTown",
> "description": "Sony's next-gen PlayStation 5 looks even better in the second round of 3D renders",
> "url": "https://www.tweaktown.com/news/67997/latest-playstation-5-renders-still-awesome-shaped-design/index.html",
> "urlToImage": "https://images.tweaktown.com/news/6/7/67997_02_latest-playstation-5-renders-make-want-ps5-right-now_full.jpg",
> "publishedAt": "2019-10-09T00:25:02Z",
> "content": "The first round of 3D renders of the next-gen (and now confirmed) PlayStation 5 console by the fine folks at
> LetsGoDigital were amazing... but the team is back with some slick new
> renders that give us a closer look at what to expect from the
> PS5.\r\nSony confir… [+1155 chars]"
> },
> {
> "source": {
> "id": "fox-news",
> "name": "Fox News"
> },
> "author": "Mariah Haas",
> "title": "Todd Chrisley, wife Julie settle $2 million Georgia tax-evasion case - Fox News",
> "description": "\"Chrisley Knows Best\" stars Julie and Todd Chrisley have reached a settlement after allegedly failing to pay
> hundreds of thousands of dollars in income taxes to the state of
> Georgia.",
> "url": "https://www.foxnews.com/entertainment/todd-chrisley-wife-julie-cleared-state-tax-evasion-charge",
> "urlToImage": "https://static.foxnews.com/foxnews.com/content/uploads/2019/06/6d97776e9e50c9d74e686f74a588e527w-c0xd-w640_h480_q80.jpg",
> "publishedAt": "2019-10-08T23:45:38Z",
> "content": "\"Chrisley Knows Best\" stars Julie and Todd Chrisley have reached a settlement after allegedly failing to pay
> hundreds of thousands of dollars in income taxes to the state of
> Georgia.\r\nA spokesman for the couple, Allan Mayer, announced on
> Tuesday that the coup… [+2421 chars]"
> }
> ] }
回答1:
Your date you are trying to parse is not in the right format. The required format you give is yyyy-MM-dd'T'HH:mm:ssX
.
This format expects a number for the timezone - even if the number is a zero ('0').
One workaround for this is to create a second SimpleDateFormat
that uses a fallback format treating the 'Z' character as a literal and ignoring it. If your first attempt at parsing fails, catch the exception and try parsing with this format - yyyy-MM-dd'T'HH:mm:ss'Z'
.
You will also need to override the timezone to force UTC.
Something like:
try {
d = input.parse(articleList[5].publishedAt)
}
catch (e: ParseException) {
try {
val fallback = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
fallback.timeZone = TimeZone.getTimeZone("UTC")
d = fallback.parse(articleList[5].publishedAt)
catch (e2: ParseException) {
// TODO handle error
}
}
Related:
- simpledateformat parsing date with 'Z' literal
- Converting ISO 8601-compliant String to java.util.Date
- how to convert UTC date to locale GMT time on android
回答2:
java.time
Since you are already using LocalDateTime
from java.time (whether built-in or through the backport, ThreeTenABP), just stick to java.time and forget everything about the legacy datetime classes like Date
and SimpleDateFormat
. It will give you simpler code, a benefit for all.
I am sorry that I can write only Java code. I trust you translate, though.
String articleList5PublishedAt = "2019-10-09T09:02:00Z";
Instant timelinePoint = Instant.parse(articleList5PublishedAt);
Instant now = Instant.now();
Duration elapsedTime = Duration.between(timelinePoint, now);
System.out.println(timelinePoint);
System.out.println(now);
System.out.println(elapsedTime.toMinutes());
When I ran this code just now, the output was:
2019-10-09T09:02:00Z 2019-10-09T13:17:01.291404Z 255
For a point on the timeline the Instant
class is the right one to use. LocalDateTime
cannot define a point on the timeline. Also the string from your JSON response, 2019-10-09T09:02:00Z
, parses directly into an Instant
, so in this way everything fits nicely together.
来源:https://stackoverflow.com/questions/58294478/java-time-format-datetimeparseexception-text-09-10-2019-could-not-be-parsed-a