2017-01-12 2 views
-2

시간대에 따라 일부 오프셋 값이있는 날짜를 교정하려고합니다. 그래서 시간대 오프셋으로 타임 스탬프를 포맷하면 SimpleDateFormat이 오프셋 값을 시간에 추가 할 것으로 예상됩니다. 여기
내가 뭘하려 :SimpleDateFormat에서 IST 시간대 오프셋을 추가하지 않았습니다.

package com.krishna.mytrials; 

import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.TimeZone; 

public class DateExperiments { 

    public static void main(String[] args) throws Exception { 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
     //Date we set in UI 
     Date today = new Date(); 
     //The long value 
     String todayBrowserLocalTimeStamp = sdf.format(today); 
     System.out.println(todayBrowserLocalTimeStamp); 
     Date todayBrowserLocalTimeStampDate = sdf.parse(todayBrowserLocalTimeStamp); 
     System.out.println("Today's browser local time stamp: " + todayBrowserLocalTimeStampDate); 
     System.out.println("And its long value:" + todayBrowserLocalTimeStampDate.getTime()); 
     System.out.println("Date generate from long:"+ new Date(todayBrowserLocalTimeStampDate.getTime())); 
     //What server does to the above mid night time stamp of browser-local time zone 
     sdf.setTimeZone(TimeZone.getTimeZone("GMT")); 
     //What we get after it applied the server time zone to browser-local date 
     //### This is the wrong date 
     SimpleDateFormat sdf2 = new SimpleDateFormat(); 
     sdf2.setTimeZone(TimeZone.getTimeZone("GMT")); 
     sdf2.applyPattern("yyyy-MM-dd HH:mm"); 
     System.out.println(sdf2.format(todayBrowserLocalTimeStampDate)); 
     String utcDateString = sdf.format(todayBrowserLocalTimeStampDate); 
     System.out.println("The above mid night time stamp of browser-local time zone" 
       + "is converted to GMT.### The wrong one:"); 
     System.out.println(utcDateString); 
     //### The wrong date constructed 
     Date utcDate = sdf.parse(utcDateString); 
     System.out.println("###Wrong date:"+utcDate); 
     //### The wrong long 
     Long utcLong = utcDate.getTime(); 
     System.out.println("###Wrong long:"+utcLong); 
     // What we will do with the GMT+05:30 
     sdf.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); 
     String dateToBeCorrected = sdf2.format(todayBrowserLocalTimeStampDate); 
     System.out.println("Date to be corrected:"+ dateToBeCorrected); 
     SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
     Date correctedDate = sdf3.parse(dateToBeCorrected); 
     System.out.println(correctedDate); 
     SimpleDateFormat sdf4 = new SimpleDateFormat(); 
     sdf4.setTimeZone(TimeZone.getTimeZone("IST")); 
     String correctedString = sdf4.format(correctedDate); 
     System.out.println("Corrected date:" + formatDateToString(correctedDate,"dd MMM yyyy hh:mm:ss a", "IST")); 


    } 

    public static String formatDateToString(Date date, String format, 
      String timeZone) { 
     // null check 
     if (date == null) return null; 
     // create SimpleDateFormat object with input format 
     SimpleDateFormat sdf = new SimpleDateFormat(format); 
     // default system timezone if passed null or empty 
     if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) { 
      timeZone = Calendar.getInstance().getTimeZone().getID(); 
     } 
     // set timezone to SimpleDateFormat 
     sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); 
     // return Date in required format with timezone as String 
     return sdf.format(date); 
    } 


} 
Here is the output: 
2017-01-12 
Today's browser local time stamp: Thu Jan 12 00:00:00 IST 2017 
And its long value:1484159400000 
Date generate from long:Thu Jan 12 00:00:00 IST 2017 
2017-01-11 18:30 
The above mid night time stamp of browser-local time zoneis converted to GMT.### The wrong one: 
2017-01-11 
###Wrong date:Wed Jan 11 05:30:00 IST 2017 
###Wrong long:1484092800000 
Date to be corrected:2017-01-11 18:30 
Wed Jan 11 18:30:00 IST 2017 
Corrected date:11 Jan 2017 06:30:00 PM 
It is supposed add 05:30. to the date. What am I doing wrong? 
+0

코드 조각이 너무 복잡합니다. 그것을 본질에 맞추십시오. –

+0

예, 질문을 업데이트하고 문제를 일으키는 코드 만 표시하십시오. –

+0

또한 빈 줄이 하나있는 메서드 내에서 하위 작업을 분리하십시오. 그것은 일을 상당히 가독성있게 만듭니다. – VGR

답변

0

당신은 그 정보를 잃어 버릴 수 있습니다 서식 및 구문 분석을 사용하여 왕복 고려해야합니다. 이것은 형식이 지정된 날짜가 원래 Date-instance보다 적은 정보를 포함 할 수 있기 때문입니다. 이 데이터 손실을 봐 : 한 (UTC에서) 2017-01-11 18:30 나 :

원래 타임 스탬프 (가변 todayBrowserLocalTimeStampDate은)이었다

String utcDateString = sdf.format(new Date(1484175600000L)); 
// 2017-01-11 
Date utcDate = sdf.parse(utcDateString); 

1484175600000L 여기 당신이 시간 부분을 벗겨 다시 제거 문자열을 구문 분석합니다. 물론, 결과 새로운 Date - 인스턴스는 해당 시간 부분을 잃어 버려야하며 이전과 같을 수 없습니다.

2017-01-11 (시간이 없음)은 IST 영역의 5 시간 30 분 후 즉, 2017-01-11T05 : 30 + 05 : 30으로 렌더링됩니다 (기억 :). 시스템 영역). 이것은 2017-01-11T00 : 00Z와 같은 순간입니다. 모두 괜찮습니다. 단지 접두어 ###Wrong date으로 표시된 라인에서 표현 된 귀하의 기대가 잘못되었습니다.

관련 문제