简体   繁体   中英

How to convert timestamp value to specific time format using react native?

In my scenario, I need to convert timestamp value to specific time format in react native. I tired below code but can't able to achieve exact formate output. How to achieve it?

 var dateTime = new Date(23456789 * 1000);
    this.setState({DateTime:('0' + dateTime.getUTCDate()).slice(-2) +
            '/' + ('0' + dateTime.getUTCMonth()).slice(-2) +
            '/' + dateTime.getUTCFullYear() +
            '' + ('0' + dateTime.getUTCHours()).slice(-2)
        });

Exact output expecting: Wed, 2/01/2000 - 1.10 AM

you can convert using the following

 var timestemp = new Date( 23456789000 );
var formatted = timestemp.format("dd/mm/yyyy hh:MM:ss");

you can get day, date, year and month like this

  var day = timestemp.getDay();
  var date = timestemp.getDate();
  var month = timestemp.getMonth() + 1;
  var year = timestemp.getFullYear();

Update

var t = new Date(23456789000);
var formatted = ('0' + t.getDate()).slice(-2) 
    + '/' + ('0' + t.getMonth()).slice(-2)
    + '/' + (t.getFullYear())
    + ' ' + ('0' + t.getHours()).slice(-2);

Output

29/08/1970 17

Update:

    var t = new Date(1589343013000);
var hours = t.getHours();
var minutes = t.getMinutes();
var newformat = t.getHours() >= 12 ? 'PM' : 'AM';  

// Find current hour in AM-PM Format 
hours = hours % 12;  

// To display "0" as "12" 
hours = hours ? hours : 12;  
minutes = minutes < 10 ? '0' + minutes : minutes; 
var formatted = 
    (t.toString().split(' ')[0]) 
    + ', ' +('0' + t.getDate()).slice(-2) 
    + '/' + ('0' + (t.getMonth() + 1) ).slice(-2)
    + '/' + (t.getFullYear())
    + ' - ' + ('0' + t.getHours()).slice(-2)
    + ':' + ('0' + t.getMinutes()).slice(-2)
    + ' ' + newformat;

Output:

Wed, 13/05/2020 - 09:40 AM

I tried this { ${new Date(23456789000).toLocaleDateString('en-GB')} }, got 29/09/1970 in output. Instead of timestamp, I used my date value fetched from database eg { ${new Date(myobject.myfield).toLocaleDateString('en-GB')} } that also worked, I've defined inteface in React that matches my db object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM