conversion unix timestamp and string with java, c++,
python and php

This blog presents the conversion method between unix timestamp and time string with java, python, c++ and php. Python time.strftim, mktime, Java SimpleDataFormat, PHP strtotime, C++ strtotime, strftime function and related demo codes are also shown. You can user this online timestamp and string converter to test the conversion result.

1. Conversion between timestamp and time string with Python

For python, you can use time.strftime() and mktime() to realize the conversion between unix timestamp and time string. Following code block is a simple demo you can refer.

copy code
1 import datetime
2 import time
4 # convert UnixTimestamp to string
5 str_time = time.strftime('%Y-%m-%d', time.localtime(timestamp))
6 # convert string to UnixTimestamp
7 timestamp = time.mktime(datetime.datetime.strptime(str_time, '%Y-%m-%d').timetuple())
copy code

2. Conversion between Unixtimestamp and time with Java

For Java, we ofter depend on class SimpleDataFormat and Date to realize the conversion between unix timestamp and time. Below is a demo code show.

copy code
1 // convert timestamp to string
2 long timeStamp = System.currentTimeMillis();
3 SimpleDateFormat df = new SimpleDateFormat ("yy-MM-dd HH:mm:ss");
4 timeStr = df.format(new Date(timeStamp));
6 // convert string to timestamp
7 timeStr = "2016-04-15 12:12:12"
8 Date date = df.parse(timeStr);
9 timeStamp = date.getTime();
copy code

3. Conversion between Unixtimestamp and time string with PHP

With PHP, we can use date()function to convert unix timestamp to string, and strtotime() function to convert string to timestamp. For example:

copy code
1 timestamp = time();
2 // convert timestamp to string
3 str_time = date('Y-m-d H:i:s', timestamp);
5 // convert string to timestamp
6 timestamp = strtotime(str_time);
copy code

4. Conversion between timestamp and time with C++

For C++ programer, you can use the function strptime() and strftime() to realize the re-conversion between timestamp and time. The demo codes can be write like this.

copy code
 1 #include <ctime>  
 3 int timestamp
 4 char strTime[20] = "2016-04-15 11:11:11";
 5 strTime[19] = '\0';
 6 struct tm tm;   
 7 // convert string time to unixtimestamp
 8 strptime(strTime, "%Y-%m-%d %H:%M:%S" , &tm); 
 9 printf("asctime:%s\n", asctime(&tm));
10 // convert unixtimestamp to string time
11 strftime(strTime, 19, "%Y-%m-%d %H:%M:%S", &tm);   
copy code

 'Y', 'm', or 'd' are format specifiers for function strftime(). You can read this strftime reference to get the detail specifiers' introductions and usages.