189

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.


update

Thanks all. 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;            
    
   }
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Hesam
  • 52,260
  • 74
  • 224
  • 365

7 Answers7

501

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();  
}
buxik
  • 2,583
  • 24
  • 31
user370305
  • 108,599
  • 23
  • 164
  • 151
  • 2
    Exactly - it's better to apply some standard form to the date string before storing it in the database. In this case http://en.wikipedia.org/wiki/ISO_8601 – denis.solonenko Dec 20 '11 at 09:35
  • 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. – Alecs Aug 24 '15 at 14:52
  • I don't believe that `SimpleDateFormat.format()` throws an exception – Someone Somewhere May 24 '19 at 13:23
  • 2
    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());` – Dheeraj Jaiswal Jun 13 '19 at 09:36
  • 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. – Viddyut Khanvilkar May 18 '21 at 07:10
19
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68
Hiren Dabhi
  • 3,693
  • 5
  • 37
  • 59
  • 2
    it's not suppose to parse String as a variable? Because this way, it's trying to parse the word "string". – Marco Dec 17 '15 at 15:49
7
     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

Janku
  • 238
  • 2
  • 10
6

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
}
Pratik
  • 30,639
  • 18
  • 84
  • 159
3

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.

deHaar
  • 17,687
  • 10
  • 38
  • 51
1
String source = "24/10/17";

String[] sourceSplit= source.split("/");

int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);

    GregorianCalendar calendar = new GregorianCalendar();
  calendar.set(anno,mese-1,giorno);
  Date   data1= calendar.getTime();
  SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");

    String   dayFormatted= myFormat.format(data1);

    System.out.println("data formattata,-->"+dayFormatted);
paolixx
  • 11
  • 3
1

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

JOG
  • 5,590
  • 7
  • 34
  • 54