quest answer
quest answer

Reputation: 95

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

Upvotes: 2

Views: 14356

Answers (2)

S N
S N

Reputation: 600

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 e.g. {${new Date(myobject.myfield).toLocaleDateString('en-GB')}} that also worked, I've defined inteface in React that matches my db object.

Upvotes: 0

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

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

Upvotes: 5

Related Questions