代码之家  ›  专栏  ›  技术社区  ›  Maheskumar Subramani

转换日期格式时发生崩溃

  •  -1
  • Maheskumar Subramani  · 技术社区  · 7 年前

    我从服务器端获取此日期格式时发生崩溃,然后我在google中进行了分析,但没有得到任何正确的解决方案。如何将此日期格式转换为下面所附的这种方式 崩溃发生在 “开始日期”:“2018-01-23T00:00:00.000-05:00” 此日期

    预期日期格式: "2018-01-24 00:43:10 -0500" 提出一些可能的解决方案。

     SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        inFormat.setTimeZone(TimeZone.getDefault());
        String date = null;
        try {
            Date toConvert = inFormat.parse(OurDate);
            date = inFormat.format(toConvert);
        } catch (ParseException e) {         
            e.printStackTrace();
        }
        return date.toString();
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Ratilal Chopda    7 年前

    试试这个

    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat output1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    
    Date d = null;
    try 
    {
          d = input.parse("2018-01-23T00:00:00.000-05:00");
    
    } 
    catch (ParseException e) 
    {
        e.printStackTrace();
    }
    String formatted = output.format(d);
    Log.i("DATE", "" + formatted);
    
    String formatted1 = output1.format(d);
    Log.i("DATE1", "" + formatted1);
    

    输出

    I/DATE: 23/01/2018
    
    I/DATE1: 2018-01-23 00:00:00 +0530
    
        2
  •  0
  •   SRB Bans    7 年前

    下面是您想要实现的工作片段:

    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 "";
        }
    }
    

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

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

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

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

    来源 https://stackoverflow.com/a/35500350/3790052