0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javaの型変換(StringとかintとかDateとかCalendar他)

Last updated at Posted at 2020-09-10

普段開発とかやってると、ぽろりと忘れてたりするので忘備用。
思いつき次第、加筆修正。

文字列⇔数値
文字列⇔文字列
日付型⇔日付型、文字列

#文字列⇔数値
###String ⇔ int

qiita.java
   //int → String
   int num = 0;
   String intToString = String.valueOf(num);

   //String → int
   String number = "123";
   int stringToInt = Integer.parseInt(number);

double型、float型、long型からのString変換も同様に行えます。
とりあえずString.valueOf()に放り込んでおけばいい……はず。

補足:(2020/09/11:修正)

qiita.java
   String number = "123";

   //String → double
   double d = Double.parseDouble(number);

   //String → float
   float f = Float.parseFloat(number);

   //String → long
   long l = Long.parseLong(number);

#文字列⇔文字列
###String ⇔ char

qiita.java
   //char → String
   char chr = 'ち';
   String charToString = String.valueOf(chr);

   //String → char
   String str = "すとりんぐ";
   char stringToChar = str.charAt(0);

   //String → char[]
   char[] stringToCharList = str.toCharArray();

   //char[] → String 
   char[] charList = new char[] { '1', '文', '字' };
   String charListToString = new String(charList);

#日付型⇔日付型、文字列
###Calendar ⇔ Date

qiita.java
   import java.util.Date;
   import java.util.Calendar;

   //Date → Calendar
   Date date = new Date();
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);

   //Calendar → Date
   Calendar cal = Calendar.getInstance();
   Date calendarToDate = cal.getTime();

###Date ⇔ String

qiita.java
   import java.text.ParseException;
   import java.text.SimpleDateFormat;
   import java.util.Date;
   
   //Date → String
   Date date = new Date();
   String dateToString = String.valueOf(date);

   //String → Date
   String day = "2020/09/10 21:00:00";
   SimpleDateFormat sdf = new SimpleDateFormat(day);
   try{
      Date stringToDate = sdf.parse(day);
   } catch(ParseException e){
      e.printStackTrace();
   }

Calendar型から直接Stringにはできなさそう。
 →String.valueOf()で変換できるにはできたけど、わかりやすい文字列ではなかった。
基本的にはCalendar ⇔ Date ⇔ Stringでいいか。

.oO(String.valueOfってたくさん用意されてるんだな……。感謝感謝)

おわり

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?