9

I want to get the current time on the device in the format: 2013-10-17 15:45:01 ?

The server sends me the date of an object in the format above as a string. Now i want to get the phones current time and then check if there is a difference of say more than 5 minutes?

So A: How can i get the devices current time in this fomat: 2013-10-17 15:45:01

B how can I work out the difference between the two.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • You might want to have a look at [SampleDateFormat](http://developer.android.com/reference/java/text/SimpleDateFormat.html) – Ye Lin Aung Oct 17 '13 at 21:38
  • You do not want to do A, since comparing string date times will be a nightmare. You want to convert the server string into a date time and then compare with the current phone time.http://stackoverflow.com/questions/3941357/string-to-date-time-object-in-android/3941395#3941395 – Simon Oct 17 '13 at 21:40
  • 1
    @YeLinAung No, never use the terrible legacy classes `SimpleDateFormat`, `Calendar`, or `Date`. They were supplanted years ago by the modern *java.time* classes with the unanimous adoption of [JSR 310](https://jcp.org/en/jsr/detail?id=310). See [my Answer](https://stackoverflow.com/a/62681240/642706) for example code. – Basil Bourque Jul 01 '20 at 16:39

6 Answers6

8

You can use SimpleDateFormat to specify the pattern you want:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date())

However, if you just want to know whether the time difference is within a certain threshold, you should probably just compare long values. If your threshold is 5 minutes, then this is 5 * 60 * 1000 milliseconds so you can use the same SimpleDateFormat by calling it's parse method and check the long values.

Example:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2013-10-13 14:54:03").getTime()
ATG
  • 1,679
  • 14
  • 25
  • You should specify a locale, e.g. `Locale.US`, as a second parameter in the `new SimpleDateFormat(...)` constructor. – caw Sep 23 '14 at 08:26
2

Date currentDate = new Date(); will initialize a new date with the current time. In addition, convert the server provided time and take the difference.

String objectCreatedDateString = "2013-10-17 15:45:01";  
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date objectCreatedDate = null;
Date currentDate = new Date();
try 
{objectCreatedDate = format.parse(objectCreatedDateString);} 
catch (ParseException e) 
{Log.e(TAG, e.getMessage());}
int timeDifferential;
if (objectCreatedDate != null)
    timeDifferential = objectCreatedDate.getMinutes() - currentDate.getMinutes();
Community
  • 1
  • 1
iamreptar
  • 1,461
  • 16
  • 29
  • 2
    You don't really have to supply System.currentTimeMillis() to java.util.Date constructor - it's automatically initialized with curent time. But you must specify new operator. – mvmn Oct 17 '13 at 21:59
2

tl;dr

Duration.between(  // Calculate time elapsed between two moments.
    LocalDateTime  // Represent a date with time-of-day but lacking the context of a time zone or offset-from-UTC.
        .parse( "2013-10-17 15:45:01".replace( " " , "T" ) )
        .atOffset( ZoneOffset.UTC )  // Returns an `OffsetDateTime` object.
        .toInstant() ,  // Returns an `Instant` object.
    Instant.now() // Capture the current moment as seen in UTC.
)
.toMinutes()
> 5

java.time

The other Answers are outdated, using terrible classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

Parse your incoming string.

String input = "2013-10-17 15:45:01" ;

Modify the input to comply with ISO 8601. I suggest you educate the publisher of your data about the ISO 8601 standard.

String inoutModified = input.replace( " " , "T" ) ;

Parse as a LocalDateTime because this input lacks an indicator of the intended offset or time zone.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

I assume that input was intended to represent a moment as seen in UTC, with an offset of zero hours minutes seconds. If so, educate the publisher of your data about appending a Z on the end to so indicate, per ISO 8601.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

Extract an object of the simpler class, Instant. This class is always in UTC.

Instant then = odt.toInstant() ;

Get current moment as seen in UTC.

Instant now = Instant.now() ; 

Calculate the difference.

Duration d = Duration.between( then , now ) ; 

Get duration as total whole minutes.

long minutes = d.toMinutes() ;

Test.

if ( minutes > 5 ) { … }

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Use SimpleDateFromat Class

DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormatter.format(date);

Also check this documentation

Ayman Mahgoub
  • 4,152
  • 1
  • 30
  • 27
0

If you can ask the server to send you an RFC3339 compliant date/time string, then Here is a simple answer to both of your questions:

public String getClientTime() {
    Time clientTime = new  Time().setToNow();
    return clientTime.format("%Y-%m-%d %H:%M:%S");
}

public int diffClientAndServerTime(String svrTimeStr) {
    Time svrTime = new Time();
    svrTime.parse3339(svrTimeStr);

    Time clientTime = new  Time();
    clientTime.setToNow();
    return svrTime.compare( svrTime, clientTime);
}
Phileo99
  • 5,581
  • 2
  • 46
  • 54
0

I was also trying this and finally this worked for me:

fun getTimeAgo(dateString: String): String {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val then = LocalDateTime.parse(dateString
            .replace(" ","T"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
        val now = LocalDateTime.now().atOffset(ZoneOffset.UTC).toInstant()
        val diff = Duration.between(then, now).seconds
        return when {
            diff < 60 -> "$diff seconds ago"
            diff < 3600 -> "${diff / 60} minutes ago"
            diff < 86400 -> "${diff / 3600} hours ago"
            else -> "${diff / 86400} days ago"
        }
    } else {
        return dateString
    }
}