Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@yutaYasunaga

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

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

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

文字列⇔数値

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ってたくさん用意されてるんだな……。感謝感謝)

おわり

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?