ユーザーのタイムゾーンを取得し、ユーザーのタイムゾーンに従ってデータベースに保存されている時間を変換するにはどうすればよいですか?詳細をご覧ください

ハマドナシル|

投稿の時間を節約できるアプリを開発しています。

私はこのコードを使用してその時間を取得しています:

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;
}

しかし、これは時間を変えていません。

これは、上記の方法を使用してデータベースに保存されpostedAtTimeた時間データベースから取得される時間)を変換しようとしている方法です。

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);

私のコードの何が問題なのか、またはこれが間違った方法であるかどうかを教えてください。

オワイスアリ

保存している時間文字列は、事後にタイムゾーンを変更するのに十分ではありません(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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ