convert timestamp into current date in android

后端 未结 10 591
滥情空心
滥情空心 2020-12-04 21:25

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-197

相关标签:
10条回答
  • 2020-12-04 21:47
    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

    0 讨论(0)
  • 2020-12-04 21:48

    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!

    0 讨论(0)
  • 2020-12-04 21:51

    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;
        }
    
    0 讨论(0)
  • 2020-12-04 21:51

    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" ) 
    )
    

    2013-09-18T07:01:51Z

    Whole seconds versus Milliseconds

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

    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?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    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.

    0 讨论(0)
  • 2020-12-04 21:52

    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();
    
    0 讨论(0)
  • 2020-12-04 21:54

    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;
    }
    
    0 讨论(0)
提交回复
热议问题