0

게시물을 게시 한 시간을 절약 할 수있는 앱을 개발 중입니다.사용자의 시간대를 얻고 데이터베이스에 저장된 시간을 사용자의 시간대에 따라 변환하는 방법은 무엇입니까? 자세한 내용을 참조하십시오

이 코드를 사용하여 시간을 받고 있어요 : 내가 원하는 것을 지금

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

것은 I가 그/그녀의 시간대를 사용하여 데이터베이스에 저장하는 시간을 사용자의 시간대를 얻을 수 및 변환 할 그의/그녀의 현지 시각.

나는이 사용하는 코드 일을 시도 :

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

데이터베이스를 변경할 수 있습니다 ...이 작업을 수행하는 방법을 알려주십시오. –

관련 문제