0

私はポストが投稿された時間を節約しているアプリケーションを開発しています。ユーザーのタイムゾーンを取得し、ユーザーのタイムゾーンに従ってデータベースに保存された時間を変換する方法は?詳細をご覧ください

私はこのコードを使用することにより、その時間を取得しています:

DateFormat currentTime = new SimpleDateFormat("h:mm a"); 
final String time = currentTime.format(Calendar.getInstance().getTime()); 

、私がしたいことは、私は、ユーザーのタイムゾーンを取得し、彼/彼女に彼/彼女のタイムゾーンを使用してデータベースに保存された時間を変換したいれます現地時間。

私は、この使用してコードをやってみました:

public String convertTime(Date d) { 
    //You are getting server date as argument, parse your server response and then pass date to this method 

    SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a"); 

    String actualTime = sdfAmerica.format(d); 

    //Changed timezone 
    TimeZone tzInAmerica = TimeZone.getDefault(); 
    sdfAmerica.setTimeZone(tzInAmerica); 

    convertedTime = sdfAmerica.format(d); 

    Toast.makeText(getBaseContext(), "actual : " + actualTime + " converted " + convertedTime, Toast.LENGTH_LONG).show(); 
    return convertedTime; 
} 

をが、これは時間を変更されていません。

String timeStr = postedAtTime; 
SimpleDateFormat df = new SimpleDateFormat("h:mm a"); 
Date date = null; 
try { 
    date = df.parse(timeStr); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 
convertTime(date); 

は私が私のコードで間違っているものを知って聞かせたりしてください:

これは私が法の上使用してデータベースに保存された時間に変換しようとしている方法である(postedAtTimeは、データベースから取得取得された時間です)これは間違った方法ですか?

答えて

1

保存している時間文字列では、事実の後にタイムゾーンを変更するには十分ではありません(h:mm aは時間、分、am/pmマーカーのみです)。このようなことをするには、元のタイムスタンプが入っていた時間帯を保存するか、常にUTCのような決定的な方法で時刻を保存する必要があります。

コード例:、仲間を返信用

final Date now = new Date(); 
    final String format = "yyyy-MM-dd HH:mm:ss"; 
    final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); 
    // Convert to UTC for persistence 
    sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 

    // Persist string to DB - UTC timezone 
    final String persisted = sdf.format(now); 
    System.out.println(String.format(Locale.US, "Date is: %s", persisted)); 

    // Parse string from DB - UTC timezone 
    final Date parsed = sdf.parse(persisted); 

    // Now convert to whatever timezone for display purposes 
    final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US); 
    displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York")); 

    final String display = displayFormat.format(parsed); 
    System.out.println(String.format(Locale.US, "Date is: %s", display)); 

出力

Date is: 2016-06-24 17:49:43 
Date is: 13:49 PM -0400 
+0

感謝。あなたはコードの一部をお勧めしますか? –

+0

DBスキーマを変更できず、日付を文字列として保持する必要があると仮定します(回答の例) –

+0

データベースを変更できます...私はこの作業をどのように行うことができますか? –

関連する問題