The Java timestamp and date string are converted to each other

Source: Internet
Author: User

Java code
  1. /**
  2. * Timestamp converted to date format string
  3. * @param seconds the exact string to the second
  4. * @param formatstr
  5. * @return
  6. */
  7. public static string timestamp2date (string seconds,string format) {
  8. if (seconds = = Null | | seconds.isempty () | | seconds.equals ("null")) {
  9. return "";
  10. }
  11. if (format = = Null | | format.isempty ()) format = "Yyyy-mm-dd HH:mm:ss";
  12. SimpleDateFormat SDF = new SimpleDateFormat (format);
  13. return Sdf.format (new Date (long.valueof (seconds+"000"));
  14. }
  15. /** 
  16. * Date format string converted to timestamp
  17. * @param date string dates
  18. * @param format such as: Yyyy-mm-dd HH:MM:SS
  19. * @return
  20. */
  21. public static string Date2timestamp (string date_str,string format) {
  22. try {
  23. SimpleDateFormat SDF = new SimpleDateFormat (format);
  24. return string.valueof (Sdf.parse (DATE_STR). GetTime ()/1000);
  25. } catch (Exception e) {
  26. E.printstacktrace ();
  27. }
  28. return "";
  29. }
  30. /** 
  31. * Get current timestamp (accurate to seconds)
  32. * @return
  33. */
  34. public static String TimeStamp () {
  35. Long time = System.currenttimemillis ();
  36. String t = string.valueof (time/1000);
  37. return t;
  38. }
  39. //Output Result:
  40. //timestamp=1417792627
  41. //date=2014-12-05 23:17:07
  42. //1417792627
  43. public static void Main (string[] args) {
  44. String TimeStamp = TimeStamp ();
  45. System.out.println ("timestamp=" +timestamp);
  46. String date = Timestamp2date (TimeStamp, "Yyyy-mm-dd HH:mm:ss");
  47. System.out.println ("date=" +date);
  48. String TIMESTAMP2 = Date2timestamp (date, "Yyyy-mm-dd HH:mm:ss");
  49. System.out.println (TIMESTAMP2);
  50. }

The Java timestamp and date string are converted to each other

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.