Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Json timestamp to normal date and time in javascript

I have a Json timestamp that I would like to convert into simple date time format using javascript.

I need the date and time in the following format : dd-mm-yyyy hr:mn

Here is an example json date from i wish to extract the timestamp: "timestamp": 1326439500

{
   "count": 2,
   "d": [
      {
         "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
         "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309201303",
         "timestamp": 1326439500,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "2388575404943858468"
      },
      {
         "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
         "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309198933",
         "timestamp": 1326439320,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "16209851193593872066"
      }
   ]
} 
like image 720
praneybehl Avatar asked Jan 20 '12 20:01

praneybehl


1 Answers

The date is being returned as milliseconds since epoch. The code below creates a JS date object:

var d = new Date(1245398693390);
var formattedDate = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var formattedTime = hours + ":" + minutes;

formattedDate = formattedDate + " " + formattedTime;

Here's a working fiddle.

like image 90
James Hill Avatar answered Sep 22 '22 11:09

James Hill