Android Format date with time zone

前端 未结 8 1348
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 13:05

I need to format the date into a specific string.

I used SimpleDateFormat class to format the date using the pattern \"yyyy-MM-dd\'T\'HH:m

相关标签:
8条回答
  • 2020-12-10 13:35

    What you can do is just add the ":" manually using substring(). I have faced this earlier and this solution works.

    0 讨论(0)
  • 2020-12-10 13:41

    You can use Joda Time instead. Its DateTimeFormat has a ZZ format attribute which does what you want.

    Link

    Big advantage: unlike SimpleDateFormat, DateTimeFormatter is thread safe. Usage:

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
        .withLocale(Locale.ENGLISH);
    
    0 讨论(0)
  • 2020-12-10 13:42

    Simply refactor this code and replace the 'Locale.getDefault()' with the Locale you need

    private SimpleDateFormat getDateFormat() {
        SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.DEFAULT, Locale.getDefault());
        String pattern = dateFormat.toLocalizedPattern();
        pattern = pattern.trim();
        dateFormat.applyLocalizedPattern(pattern);
        return dateFormat;
    }
    

    //And here is the usage

    SimpleDateFormat sdf = getDateFormat();

    sdf.format(new Date());

    0 讨论(0)
  • 2020-12-10 13:44

    Why not just do it manually with regexp?

    String oldDate = "2013-01-04T15:51:45+0530";
    String newDate = oldDate.replaceAll("(\\+\\d\\d)(\\d\\d)", "$1:$2");
    

    Same result, with substring (if performance is an issue).

    String oldDate = "2013-01-04T15:51:45+0530";
    int length = oldDate.length();
    String newDate = oldDate.substring(0, length - 2) + ':' + oldDate.substring(length - 2);
    
    0 讨论(0)
  • 2020-12-10 13:46

    If you want the date for a different timeZone (which the title suggests)

      val nowMillsUTC = System.currentTimeMillis()
    
      val timeZoneID = "Australia/Perth"
      val tz = TimeZone.getTimeZone(timeZoneID)
    
      val simpleDateFormat = SimpleDateFormat("HH.mm  dd.MMM.yyyy", Locale.getDefault())
      simpleDateFormat.setTimeZone(tz)
      val resultTxt = simpleDateFormat.format(nowMillsUTC)
    
      print(timeZoneID + " -> " + resultTxt)
      //   Australia/Perth -> 19.59  21.Mar.2019
    
    0 讨论(0)
  • 2020-12-10 13:49

    You can also use "ZZZZZ" instead of "Z" in your pattern (according to documentation). Something like this

        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);      
        Log.e(C.TAG, "formatted string: "+sdf.format(c.getTime()));
    
    0 讨论(0)
提交回复
热议问题