Numeric ⇒ String conversion
Numeric to string conversion is,String.valueof() Use the
String str = String.valueOf(num);
There are also other ways to write this.
String str = Integer.toString(num); String str = "" + num;
The final "" + num takes advantage of a Java feature that treats numbers as strings when concatenated with strings.
The last approach is the simplest to describe, but if someone who does not have a thorough understanding of Java's characteristics sees it, it will take time to decipher the intent.
String ⇒ Numeric conversion
String to numeric conversion is,Integer.parseInt() Use the
int num = Integer.parseInt(str);
Note that a NumberFormatException will be thrown if the conversion fails for some reason, such as the presence of characters or a number that does not fit into the type.
Date ⇒ String conversion
Converting a date to a string is a bit more complicated than number to string.
first (of all) SimpleDateFormat Create an instance of Specify the date format when you create it. This will be the format when made into a string.
Finally. SimpleDateFormat.format() to a string.
sample code
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String str = sdf.format(date);
System.out.println("日付型 = " + date);
System.out.println("文字列 = " + str);
}
Output Results:
日付型 = Sat Nov 02 12:11:55 UTC 2019
文字列 = 2019/11/02 12:11:55
String ⇒ Date conversion
For string to date conversion,SimpleDateFormat.parse method.
Create a SimpleDateFormat as in the date ⇒ string case. When created, the date format is specified, which matches the date format of the string to be converted.
Finally. SimpleDateFormat.parse() to convert to a date (Date).
sample code
public static void main(String[] args) {
try {
String strDate = "2019/11/01 12:34:56";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
Date date = sdf.parse(strDate);
System.out.println("文字列 = " + strDate);
System.out.println("日付型 = " + date);
} catch (ParseException e) {
//例外処理
}
}
Output Results:
文字列 = 2019/11/01 12:34:56
日付型 = Fri Nov 01 00:34:56 UTC 2019
Note that the parse method throws a ParseException, which must be enclosed in a try-catch statement or re-thrown.
Numeric ⇔ Date Conversion
Unfortunately, there are no methods designed to convert numbers to dates or dates to numbers. Both need to go through conversion to string once.