文字列yyyy-MM-dd HH:mm:ss
(UTCタイムゾーン)の形式で日付を取得し、それをEEEE d(st, nd, rd, th) MMMM yyyy HH:mm
(デバイスのデフォルトのタイムゾーン)にするためのコードを用意しました。解析と書式の日付
しかし、私のやり方の問題は、コードが乱雑で非効率的に見えることです。より効率的にするために同じ日付を何度もフォーマットし解析することなく、私が望むものを達成する方法はありますか?その他の改善点は?
は、好ましくは改善するために多くはおそらくないのAndroid APIレベルにSimpleDateFormat
14.
String inputExample = "2017-06-28 22:44:55";
//Converts UTC to Device Default (Local)
private String convertUTC(String dateStr) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date temp = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String local = df.format(temp);
Date localDate = df.parse(dateStr);
SimpleDateFormat outputDF1 = new SimpleDateFormat("EEEE ");
SimpleDateFormat outputDF2 = new SimpleDateFormat(" MMMM yyyy HH:mm");
return outputDF1.format(temp) + prefix(local) + outputDF2.format(temp);
} catch(java.text.ParseException pE) {
Log.e("", "Parse Exception", pE);
return null;
}
}
private String prefix(String dateStr) {
try {
SimpleDateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date temp = outputDF.parse(dateStr);
SimpleDateFormat df = new SimpleDateFormat("d");
int d = Integer.parseInt(df.format(temp));
if(1 <= d && d <= 31) {
if(11 <= d && d <= 13)
return d + "th";
switch (d % 10) {
case 1: return d + "st";
case 2: return d + "nd";
case 3: return d + "rd";
default: return d + "th";
}
}
Log.e("", "Null Date");
return null;
} catch(java.text.ParseException pE) {
Log.e("", "Parse Exception", pE);
return null;
}
}
[codereview.se]に属しているため、この質問を議論の対象外としています。 – shmosel
@shmoselそれを指摘してくれてありがとう。私はそこに投稿します – Dan
あなたのコードをプロファイリングして、パフォーマンスの低下の原因を突き止める必要があります。 「面倒な」部分に関しては、java.util.date APIは広く「厄介」とみなされています。多くのことができません。コードをリファクタリングして、よりクリーンな方法を見つけてください。リファクタリングを開始する前に、単体テストの包括的なスイートがあることを確認してください。 – Egor