Convert Android's date Strings to date objects

前端 未结 2 1431
北荒
北荒 2021-01-21 06:27

In Android, the date of every event (such as birthdays and anniversaries) is saved in String format, e.g. \"2011-12-24\".

This is at least the case for my phone. Some ot

相关标签:
2条回答
  • 2021-01-21 06:43
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yy");
            Date tempDate;
            try {
                tempDate = myDateFormat.parse("24/12/2011");
                  long milliseconds=tempDate.getTime();
                  Toast.makeText(getApplicationContext(), milliseconds+"", 1).show();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
    0 讨论(0)
  • 2021-01-21 06:47

    Android works with date objects. Anytime you need to parse a date from string is because that date has been serialized, most likely in a file. In that case, you would know the format that was used. Date object is used in preferences, date object is used almost everywhere I can think of that relates to shared services, activites, etc. This means, there's almost never a need to parse string from date unless, like I said you're working with serialized source, reading it from a web service etc. If you can tell us your scenario, you might get more specific answer.

    You can get the currently set date format like this:

    DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    
    0 讨论(0)
提交回复
热议问题