Home  >  Article  >  Backend Development  >  How to convert date to string in php

How to convert date to string in php

王林
王林Original
2020-10-12 09:48:432709browse

How to convert date to string in php: You can use SimpleDateFormat.format to convert date to String, such as [str3 = format1.format(date1);].

How to convert date to string in php

Conversion of Date and String formats

(Recommended tutorial: php video tutorial)

SimpleDateFormat.format converts date into String.

SimpleDateFormat.parse converts String into date.

Code test:

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
Date date1 = null;
Date date2 = null;
String str1 = "2009-02-14 12:00:00";
String str2 = "2009年02月14日 12时00分00秒";

// String转Date:String 必须严格按照定义的格式
try {
date1 = format1.parse(str1);
date2 = format2.parse(str2);
} catch (ParseException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("date1= "+date1);
System.out.println("date2= "+date2);

//Date转StringString 
str3 = null;
String str4 = null;
str3 = format1.format(date1);
str4 = format2.format(date2);
System.out.println("str1= "+str3);
System.out.println("str2= "+str4);

Related recommendations:php training

The above is the detailed content of How to convert date to string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:mampHow to modify php.iniNext article:mampHow to modify php.ini