如何格式化2016-02-12T15:23:20 + 02:00时间 [英] How to format 2016-02-12T15:23:20+02:00 time

查看:96
本文介绍了如何格式化2016-02-12T15:23:20 + 02:00时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我们的网络服务中获取上述日期格式。我对如何设置日期格式有一个想法,只是对日期以字符串形式出现的事实有疑问。

I'm getting the above Date format from our webservice. I have an idea on how to format the date, im just having issues with the fact it comes down as a string.

我尝试了,但我需要将其作为字符串返回,这在某种意义上不是问题。

I have tried this but I need to return it as a String, which in a way isn't a problem.

这是我尝试过的方法,但是会引发异常:

This is what I have tried but it throws an Exception:


java .text.ParseException:无法解析的日期:
2016-02-26T00:00:00 + 02:00(在偏移量4处)

java.text.ParseException: Unparseable date: "2016-02-26T00:00:00+02:00" (at offset 4)

代码:

  public static String formatDate(String unFormattedTime) {
    String formattedTime;
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("dd MMM HH:mm");
      Date date = sdf.parse(unFormattedTime);

      formattedTime = sdf.format(date);
      return formattedTime;

    } catch (ParseException e) {
      e.printStackTrace();
    }

    return "";
  }

如何将其格式化为dd MMM HH:mm?

How could I format it in a format like dd MMM HH:mm?

推荐答案

在这里,您可以看到要实现的目标片段:

Here you are with a working snippet of what you want to achieve:

public class FormatDateExample {
    public static void main(String[] args) {
        String date =  "2016-02-26T00:00:00+02:00";
        System.out.println(formatDate(date));

    }

    public static String formatDate(String unFormattedTime) {
         String formattedTime;
         try {
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
             Date date = sdf.parse(unFormattedTime);

             sdf = new SimpleDateFormat("dd MMM HH:mm");
             formattedTime = sdf.format(date);

             return formattedTime;

        } catch (ParseException e) {
             e.printStackTrace();
        }

        return "";
    }
}

首先,您必须使用给定的格式解析日期您有

First you have to parse the date with the given format you have

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = sdf.parse(unFormattedTime);

然后,您必须将该日期格式化为所需的格式 dd MMM HH:mm

Then you have to format that date to the desired format "dd MMM HH:mm"

sdf = new SimpleDateFormat("dd MMM HH:mm");
formattedTime = sdf.format(date);

这篇关于如何格式化2016-02-12T15:23:20 + 02:00时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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