Android: How can I Convert String to Date?

291,596

Solution 1

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

Solution 2

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

Solution 3

     import java.text.ParseException;
     import java.text.SimpleDateFormat;
     import java.util.Date;
     public class MyClass 
     {
     public static void main(String args[]) 
     {
     SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

     String dateInString = "Wed Mar 14 15:30:00 EET 2018";

     SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");


     try {

        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatterOut.format(date));

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

here is your Date object date and the output is :

Wed Mar 14 13:30:00 UTC 2018

14 Mar 2018

Solution 4

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

Solution 5

You can use java.time in Android now, either by using Android API Desugaring or importing the ThreeTenAbp.

With java.time enabled, you can do the same operations with less code and less errors.

Let's assume you are passing a String containing a datetime formatted in ISO standard, just as the currently accepted answer does.
Then the following methods and their usage in a main may show you how to convert from and to String:

public static void main(String[] args) {
    String dtStart = "2010-10-15T09:27:37Z";
    ZonedDateTime odt = convert(dtStart);
    System.out.println(odt);
}

and

public static void main(String[] args) {
    String dtStart = "2010-10-15T09:27:37Z";
    OffsetDateTime odt = convert(dtStart);
    System.out.println(odt);
}

will print the line

2010-10-15T09:27:37Z

when there are the corresponding methods

public static OffsetDateTime convert(String datetime) {
    return OffsetDateTime.parse(datetime);
}

or

public static ZonedDateTime convert(String datetime) {
    return ZonedDateTime.parse(datetime);
}

but of course not in the same class, that would not compile...

There's a LocalDateTime, too, but that would not be able to parse a zone or offset.

If you want to use custom formats for parsing or formatting output, you can utilize a DateTimeFormatter, maybe like this:

public static void main(String[] args) {
    String dtStart = "2010-10-15T09:27:37Z";
    String converted = ZonedDateTime.parse(dtStart)
                                    .format(DateTimeFormatter.ofPattern(
                                                    "EEE MMM d HH:mm:ss zz uuuu",
                                                    Locale.ENGLISH
                                                )
                                            );
    System.out.println(converted);
}

which will output

Fri Oct 15 09:27:37 Z 2010

For an OffsetDateTime, you would need to adjust the pattern a little:

public static void main(String[] args) {
    String dtStart = "2010-10-15T09:27:37Z";
    String converted = OffsetDateTime.parse(dtStart)
                                    .format(DateTimeFormatter.ofPattern(
                                                    "EEE MMM d HH:mm:ss xxx uuuu",
                                                    Locale.ENGLISH
                                                )
                                            );
    System.out.println(converted);
}

This will produce a (slightly) different output:

Fri Oct 15 09:27:37 +00:00 2010

That's because a ZonedDateTime considers named time zones with changing offsets (due to daylight saving times or anything similar) while an OffsetDateTime just knows an offset from UTC.

Share:
291,596

Related videos on Youtube

Hesam
Author by

Hesam

Do you want to know more about me, find me in LinkedIn

Updated on July 17, 2022

Comments

  • Hesam
    Hesam almost 2 years

    I store current time in database each time application starts by user.

    Calendar c = Calendar.getInstance();
        String str = c.getTime().toString();
        Log.i("Current time", str);
    

    In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?

    Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.

    Thanks

    ======> update

    Thanks dear guys. I used following code:

    private boolean isPackageExpired(String date){
            boolean isExpired=false;
            Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");        
            if (new Date().after(expiredDate)) isExpired=true;
    
            return isExpired;
        }
    
        private Date stringToDate(String aDate,String aFormat) {
    
          if(aDate==null) return null;
          ParsePosition pos = new ParsePosition(0);
          SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
          Date stringDate = simpledateformat.parse(aDate, pos);
          return stringDate;            
    
       }
    
  • denis.solonenko
    denis.solonenko over 12 years
    Exactly - it's better to apply some standard form to the date string before storing it in the database. In this case en.wikipedia.org/wiki/ISO_8601
  • Alecs
    Alecs over 8 years
    For a more strictly working solution on "string to date", it's convenient to add "format.setLenient(false);" before the try...catch block. In this way the check of a formerly correct string date will be better.
  • Marco
    Marco over 8 years
    it's not suppose to parse String as a variable? Because this way, it's trying to parse the word "string".
  • Someone Somewhere
    Someone Somewhere almost 5 years
    I don't believe that SimpleDateFormat.format() throws an exception
  • Dheeraj Jaiswal
    Dheeraj Jaiswal almost 5 years
    if your SDK version greater or equal to Marshmallow then use like this SimpleDateFormat dateFormat =new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"", Locale.getDefault());
  • Maryoomi1
    Maryoomi1 over 4 years
    Thank you so much!
  • Viddyut Khanvilkar
    Viddyut Khanvilkar almost 3 years
    i am tring to convert string in format of dd/mm/Y to date but when i convert, no matter what date i choose, it returns day as 27, month and year are correctly returned.