60

I have a problem in displaying the date,I am getting timestamp as 1379487711 but as per this the actual time is 9/18/2013 12:31:51 PM but it displays the time as 17-41-1970. How to show it as current time.

for displaying time I have used the following method:

private String getDate(long milliSeconds) {
    // Create a DateFormatter object for displaying date in specified
    // format.
    SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    // Create a calendar object that will convert the date and time value in
    // milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis((int) milliSeconds);
    return formatter.format(calendar.getTime());
} 
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
jkk
  • 611
  • 1
  • 5
  • 4
  • 2
    Are you sure this is in mili-seconds and not simple seconds? use this to check your time: http://www.onlineconversion.com/unix_time.htm – Sean Sep 21 '13 at 07:10
  • When I checked the answer is Wed, 18 Sep 2013 07:01:51 UTC – jkk Sep 21 '13 at 07:20
  • I am using timestamp as long time = System.currentMilliSeconds; – jkk Sep 21 '13 at 07:22
  • You can try this if you want, for me it works perfectly. [Firebase Functions](https://stackoverflow.com/questions/38593245/how-to-get-current-timestamp-of-firebase-server-in-milliseconds/59448648#59448648) – AllanRibas Jun 07 '20 at 16:32

11 Answers11

120
private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

notice that I put the time in setTimeInMillis as long and not as int, notice my date format has MM and not mm (mm is for minutes, and not months, this is why you have a value of "41" where the months should be)

for Kotlin users:

fun getDate(timestamp: Long) :String {
   val calendar = Calendar.getInstance(Locale.ENGLISH)
   calendar.timeInMillis = timestamp * 1000L
   val date = DateFormat.format("dd-MM-yyyy",calendar).toString()
   return date
}

COMMENT TO NOT BE REMOVED: Dear Person who tries to edit this post - completely changing the content of the answer is, I believe, against the conduct rules of this site. Please refrain from doing so in the future. -LenaBru

Emil
  • 140
  • 1
  • 8
Lena Bru
  • 13,521
  • 11
  • 61
  • 126
15

For converting time stamp to current time

Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
java.util.Date currenTimeZone=new java.util.Date((long)1379487711*1000);
Toast.makeText(TimeStampChkActivity.this, sdf.format(currenTimeZone), Toast.LENGTH_SHORT).show();
Kaushik
  • 6,150
  • 5
  • 39
  • 54
10

convert timestamp into current date:

private Date getDate(long time) {    
    Calendar cal = Calendar.getInstance();
       TimeZone tz = cal.getTimeZone();//get your local time zone.
       SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
       sdf.setTimeZone(tz);//set time zone.
       String localTime = sdf.format(new Date(time) * 1000));
       Date date = new Date();
       try {
            date = sdf.parse(localTime);//get local date
        } catch (ParseException e) {
            e.printStackTrace();
        }
      return date;
    }
Voy
  • 5,286
  • 1
  • 49
  • 59
kyogs
  • 6,766
  • 1
  • 34
  • 50
6
  DateFormat df = new SimpleDateFormat("HH:mm", Locale.US);
  final String time_chat_s = df.format(time_stamp_value);

The time_stamp_value variable type is long

With your code it will look something like so:

private String getDate(long time_stamp_server) {

    SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    return formatter.format(time_stamp_server);
} 

I change "milliseconds" to time_stamp_server. Consider changing the name of millisecond to "c" or to something more global. "c" is really good because it relates to time and to computing in much more global way than milliseconds does. So, you do not necessarily need a calendar object to convert and it should be as simple as that.

sivi
  • 10,654
  • 2
  • 52
  • 51
4

tl;dr

You have a number of whole seconds since 1970-01-01T00:00:00Z rather than milliseconds.

Instant
.ofEpochSecond( 1_379_487_711L )
.atZone( 
    ZoneId.of( "Africa/Tunis" ) 
)
.toLocalDate()
.format(
    DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) 
)

See this code run at Ideone.com.

18-09-2013

Whole seconds versus Milliseconds

As stated above, you confused a count-of-seconds with a count-of-milliseconds.

Your confusion demonstrates why using a mere integer to represent a moment is a poor choice. Instead, use text, always in standard ISO 8601 format.

Using java.time

The other Answers may be correct but are outdated. The troublesome old date-time classes used there are now legacy, supplanted by the java.time classes. For Android, see the last bullets below.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.ofEpochSecond( 1_379_487_711L ) ;

instant.toString(): 2013-09-18T07:01:51Z

Apply the time zone through which you want to view this moment.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString(): 2013-09-18T03:01:51-04:00[America/Montreal]

Generate a string representing this value in your desired format.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = zdt.format( f ) ;

18-09-2013

See this code run live at IdeOne.com.


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.

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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

If your result always returns 1970, try this way :

Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();

You need to multiple your TS value by 1000

It’s so easy to use it.

Paras Andani
  • 99
  • 1
  • 6
2

I got this from here: http://www.java2s.com/Code/Android/Date-Type/CreateDatefromtimestamp.htm

None of the above answers worked for me.

Calendar c = Calendar.getInstance();
c.setTimeInMillis(Integer.parseInt(tripBookedTime) * 1000L);
Date d = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
return sdf.format(d);

And by the way: ("dd-MM-yyyy", cal) is not recognized by Android - "Cannot resolve method".

ekashking
  • 387
  • 6
  • 19
  • 1
    These terrible date-time classes were supplanted years ago by the modern *java.time* classes. Suggesting their use in 2019 is poor advice. – Basil Bourque Jun 26 '19 at 00:29
  • Well, it works without single trouble or any warnings or notations from the latest AndroidStudio 3.4.1 – ekashking Jun 26 '19 at 00:33
  • Android Studio does not know about the quality of the libraries, only humans know that. – Basil Bourque Jun 26 '19 at 01:26
  • Ok, any suggestions on how to convert timestamp from MySQL to the string with "MMM dd, yyyy" format??? Cause NO OTHER answers working on this page!!! – ekashking Jun 26 '19 at 01:30
  • 1
    (A) You should not be asking for a date-time from the database as a a mere integer number (a count from epoch). You should be retrieving a date-time object, a `java.time.OffsetDateTime` object. (B) If you do retrieve an integer count-from-epoch of first moment of 1970 in UTC, what about the `Instant.ofEpochSecond( 1_379_487_711L ).atZone( ZoneId.of( "Africa/Tunis" ) ).format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) )` given in [my Answer](https://stackoverflow.com/a/46416290/642706) did not work for you? See that [one-liner run live at IdeOne.com](https://ideone.com/Tz7iJB). – Basil Bourque Jun 26 '19 at 01:39
  • If you post a detailed Question about your date-time database problem, I'll try to answer it. – Basil Bourque Jun 26 '19 at 01:55
1

If you want show chat message look like what up app, then use below method. date format you want change according to your requirement.

public String DateFunction(long timestamp, boolean isToday)
{
    String sDate="";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    Calendar c = Calendar.getInstance();
    Date netDate = null;
    try {
        netDate = (new Date(timestamp));
        sdf.format(netDate);
        sDate = sdf.format(netDate);
        String currentDateTimeString = sdf.format(c.getTime());
        c.add(Calendar.DATE, -1);
        String yesterdayDateTimeString =  sdf.format(c.getTime());
        if(currentDateTimeString.equals(sDate) && isToday) {
            sDate = "Today";
        } else if(yesterdayDateTimeString.equals(sDate) && isToday) {
            sDate = "Yesterday";
        }
    } catch (Exception e) {
        System.err.println("There's an error in the Date!");
    }
    return sDate;
}
Styx
  • 9,863
  • 8
  • 43
  • 53
Vinod Makode
  • 953
  • 7
  • 7
  • 2
    FYI, these troublesome old classes are now legacy, supplanted by the java.time classes. For Android see the ThreeTen-Backport and ThreeTenABP projects. – Basil Bourque Sep 25 '17 at 15:10
1

current date and time:

 private String getDateTime() {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        Long time = System.currentTimeMillis();
        calendar.setTimeInMillis(time);

       //dd=day, MM=month, yyyy=year, hh=hour, mm=minute, ss=second.

        String date = DateFormat.format("dd-MM-yyyy hh:mm:ss",calendar).toString();
        return date;
    }

Note: If your result always returns 1970, try this way :

Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calender.setTimeInMillis(time * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", calendar).toString();
Shoaib Kakal
  • 1,090
  • 2
  • 16
  • 32
0

USING NEW--> JAVA.TIME FOR ANDROID APPS TARGETING >API26

SAVING DATETIMESTAMP

 @RequiresApi(api = Build.VERSION_CODES.O)
    public long insertdata(String ITEM, String INFORMATION, Context cons)
    {
        long result=0; 

            // Create a new map of values, where column names are the keys
            ContentValues values = new ContentValues();
            
            LocalDateTime INTIMESTAMP  = LocalDateTime.now();
            
            values.put("ITEMCODE", ITEM);
            values.put("INFO", INFORMATION);
            values.put("DATETIMESTAMP", String.valueOf(INTIMESTAMP));
        
            try{

                result=db.insertOrThrow(Tablename,null, values);            

            } catch (Exception ex) {
            
                Log.d("Insert Exception", ex.getMessage());
                
            }

            return  result;

    }   

INSERTED DATETIMESTAMP WILL BE IN LOCAL DATETIMEFORMAT [ 2020-07-08T16:29:18.647 ] which is suitable to display.

Hope it helps!

MdBasha
  • 423
  • 4
  • 16
0

Try this, it works perfect

    long time = us.getTimeStamp();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY - hh:mm a");
    Log.d("rajbhai", String.valueOf(us.getTimeStamp()));
    holder.binding.chaterName.setText(dateFormat.format(new Date(time)));
  • 1
    Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. Also your format pattern string is incorrect (this time I mean it, have double-checked). – Ole V.V. Sep 19 '22 at 16:27