code

자바 : 문자열을 타임 스탬프로 변환

codestyles 2020. 12. 29. 07:05
반응형

자바 : 문자열을 타임 스탬프로 변환


문자열을 TimeStamp로 변환하는 동안 문제가 있습니다. 형식의 날짜가있는 배열이 있고 형식 yyyy-MM-dd을 변경하고 싶습니다 yyyy-MM-dd HH:mm:ss.SSS. 그래서이 코드를 사용합니다.

final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;

DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);

Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);

그리고 나는 다음과 같은 결과를 얻습니다.

2009-10-20 00 : 00 : 00.000

2009-10-20 00 : 00 : 00.0

하지만 내가 단순히하려고 할 때

String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);

올바른 결과를 얻습니다.

2011-10-02 18 : 48 : 05.123

내가 뭘 잘못하고 있는지 알아? 도와 주셔서 감사합니다.


올바른 결과를 얻으려면 다음 단계를 따르십시오.

try {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
    Date parsedDate = dateFormat.parse(yourString);
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) { //this generic but you can control another types of exception
    // look the origin of excption 
}

그주의 사항 .parse(String)을 던질 수있다 ParseException.


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Util {
  public static Timestamp convertStringToTimestamp(String strDate) {
    try {
      DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
       // you can change format of date
      Date date = formatter.parse(strDate);
      Timestamp timeStampDate = new Timestamp(date.getTime());

      return timeStampDate;
    } catch (ParseException e) {
      System.out.println("Exception :" + e);
      return null;
    }
  }
}

나는 현대적인 대답에 기여하고 싶습니다. 2013 년에이 질문을 받았을 때 Timestamp, 예를 들어 데이터베이스에 날짜-시간을 저장하기 위해 클래스를 사용하는 것이 옳았습니다. 오늘날 수업은 오래되었습니다. 최신 Java 날짜 및 시간 API는 3 년 반 전인 2014 년 봄에 Java 8과 함께 나왔습니다. 대신 이것을 사용하는 것이 좋습니다.

상황에 따라 정확한 요구 사항에 따라 다음 두 가지 대체 방법이 있습니다 Timestamp.

  • Instant타임 라인의 한 지점입니다. 대부분의 경우 이것을 사용하는 것이 가장 안전하다고 생각합니다. Instant시간대의 독립적이며 일반적으로도 클라이언트 장치와 데이터베이스 서버가 다른 시간대를 실행하는 상황에서 잘 작동합니다.
  • LocalDateTime 2011-10-02 18 : 48 : 05.123 (질문 인용)과 같이 시간대가없는 날짜 및 시간입니다.

최신 JDBC 드라이버 (JDBC 4.2 이상) 및 데이터베이스 액세스를위한 기타 최신 도구는 Instant또는 a LocalDateTime를 데이터 유형의 데이터베이스 열에 저장합니다 timestamp. 이 답변에서 사용하는 클래스와 다른 날짜 시간 클래스는 java.timeJSR-310 으로 알려진 최신 API에 속합니다 .

문자열을로 변환하는 것이 가장 쉽기 LocalDateTime때문에 먼저 살펴 보겠습니다.

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    String text = "2011-10-02 18:48:05.123";
    LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
    System.out.println(dateTime);

이것은 인쇄

2011-10-02T18:48:05.123

문자열이 yyyy-MM-dd 형식이면 대신 다음을 수행하십시오.

    String text = "2009-10-20";
    LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
    System.out.println(dateTime);

이것은 인쇄

2009-10-20T00:00

또는 더 나은 방법은 출력 LocalDate.parse()을 데이터 유형의 데이터베이스 열에 저장하는 것 date입니다.

두 경우 모두 a LocalDateTime에서 로 변환하는 절차 Instant는 다음과 같습니다.

    Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
    System.out.println(ts);

I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:

    Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date date = formatter.parse(dateString);

Timestamp timestamp = new Timestamp(date.getTime());

System.out.println(timestamp);

DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());

The easy way to convert String to java.sql.Timestamp:

Timestamp t = new Timestamp(DateUtil.provideDateFormat().parse("2019-01-14T12:00:00.000Z").getTime());

DateUtil.java:

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

public interface DateUtil {

  String ISO_DATE_FORMAT_ZERO_OFFSET = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  String UTC_TIMEZONE_NAME = "UTC";

  static SimpleDateFormat provideDateFormat() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_DATE_FORMAT_ZERO_OFFSET);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone(UTC_TIMEZONE_NAME));
    return simpleDateFormat;
  }
}

first convert your date string to date then convert it to timestamp by using following set of line

Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;

I'm sure the solution is that your oldDateString is something like "2009-10-20". Obviously this does not contain any time data lower than days. If you format this string with your new formatter where should it get the minutes, seconds and milliseconds from?

So the result is absolutely correct: 2009-10-20 00:00:00.000

What you'll need to solve this, is the original timestamp (incl. time data) before your first formatting.


can you try it once...

String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
    if(dob!=null && !dob.isEmpty() && dob != "")
    {
    c.setTime(df.parse(dob));
    int month=c.get(Calendar.MONTH);
    month=month+1;
    dobis=c.get(Calendar.YEAR)+"-"+month+"-"+c.get(Calendar.DAY_OF_MONTH);
    }

}

ReferenceURL : https://stackoverflow.com/questions/18915075/java-convert-string-to-timestamp

반응형