0

I am converting String to Timestamp but output format has extra '0'.

Below is the code.

Code:

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StringToTimeStamp {

    public static void main(String[] args) {

        String date = "2017-01-01T00:00:00.000-05:00";


        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");


        try {
            java.util.Date parsedDate = dateFormat.parse(date);
            System.out.println(parsedDate);
            Timestamp time = new Timestamp(parsedDate.getTime());
            System.out.println(time);

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output

Sun Jan 01 00:00:00 IST 2017
2017-01-01 00:00:00.0

Expected output

Sun Jan 01 00:00:00 IST 2017
2017-01-01 00:00:00

I am not able to understand why extra '0' is there in output?

JDK version : 1.8.0_191

EDIT

I tried formatting my timestamp instance like this :

System.out.println(dateFormat.format(time));

It gave below output :

Sun Jan 01 00:00:00 IST 2017
2017-01-01T00:00:00

It removed '0' but added 'T'.

A Learner
  • 157
  • 1
  • 5
  • 16
  • Can you kindly tell which Java version are you using? – darshgohel Apr 04 '19 at 05:52
  • 4
    Check this https://stackoverflow.com/questions/42372261/unexplained-zero-added-when-going-from-java-util-date-to-java-sql-timestamp – Atul Sharma Apr 04 '19 at 05:52
  • 1
    At that point, you are not printing a formatted String, but the timestamp instance. The formatting doesn't apply to that – Stultuske Apr 04 '19 at 05:53
  • @darshgohel jdk1.8.0_191 – A Learner Apr 04 '19 at 05:54
  • @Stultuske but how to get the expected output? – A Learner Apr 04 '19 at 05:55
  • @Stultuske okay so you mean I need to format it as well. – A Learner Apr 04 '19 at 05:56
  • You can checkout the link provided by @AtulSharma – darshgohel Apr 04 '19 at 05:56
  • Use another formatter – Scary Wombat Apr 04 '19 at 05:56
  • @AtulSharma but then output is like : 2017-01-01T00:00:00 and not 2017-01-01 00:00:00 – A Learner Apr 04 '19 at 05:58
  • @ScaryWombat which one? I have updated my question again , can you please check. – A Learner Apr 04 '19 at 06:00
  • Either use formatters or got for string manipulation choice is yours. – RAHUL ROY Apr 04 '19 at 06:01
  • what part of `another` did you not understand in my above comment? – Scary Wombat Apr 04 '19 at 06:24
  • @AtulSharma That situation is different. They are getting 00:00:00.001 instead of 00:00:00.01, which is a different *value*. This question is about a different *format*. – Ole V.V. Apr 04 '19 at 06:49
  • I recommend you don’t use `SimpleDateFormat`, `Date` and `Timestamp`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead use `OffsetDateTime` and `Instant`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 04 '19 at 06:50
  • Possible duplicate of [Formatting timestamp in Java](https://stackoverflow.com/questions/23692117/formatting-timestamp-in-java) and/or [timestamp formatting in scala [duplicate\]](https://stackoverflow.com/questions/52841451/timestamp-formatting-in-scala) – Ole V.V. Apr 04 '19 at 06:57
  • 1
    While not parsing the fractional seconds of your string gives an inaccuracy at worst, you are also ignoring the offset, -05:00, which introduces an error. If IST is India Standard Time (many other interpretations exist), then you string represents a point in time of Sun Jan 01 **10:30**:00 IST 2017. `System.out.println(time);` implicitly calls `time.toString`, and the `toString` method of the `Timestamp` class (that you should avoid using anyway) always prints at least one decimal on the seconds, there is no way to avoid that. – Ole V.V. Apr 04 '19 at 10:24
  • @OleV.V. Thanks for detailed explanation. – A Learner Apr 05 '19 at 05:02

4 Answers4

3

Smart objects, not dumb strings

Be sure you understand that a date-time object is not text, is not the same as a String.

A date-time object can generate a string containing text that represents the value. That string can be created following all kinds of different formats localized for all kinds of locales. And a date-time object can be instantiated by parsing an input string, after translating into a value for the object. But the string and the date-time object are separate and distinct.

Use date-time objects throughout your codebase whenever practical, rather than relying on mere strings.

java.time

You are using terrible date-time classes that were supplanted years ago by the java.time classes. Never use java.util.Date nor java.sql.Timestamp.

Parse your input string as a OffsetDateTime object.

String input = "2017-01-01T00:00:00.000-05:00" ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;

If your goal is storing this value as a member variable in your class, make that member variable of type OffsetDateTime rather than String.

The toString method generates text in standard ISO 8601 format.

To generate text in other formats, use the DateTimeFormatter class. This class has been covered many times already, so search Stack Overflow to learn more.

Be wary of generating strings that represent a moment yet omit an indicator of the time zone or offset-from-UTC. That is like reporting an amount of money while neglecting to mention the currency.

DateTimeFormatter f =  DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = odt.format( f ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

You can try the following code. I have added a new formatter and converted the timestamp to the correct format you need.

I have added the following approach assuming that you need to format a date and print it and at the same time to format the timestamp and convert it too.

public static void main(String args[]) throws ParseException {
    String date = "2017-01-01T00:00:00.000-05:00";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
        java.util.Date parsedDate = dateFormat.parse(date);
        System.out.println(parsedDate);
        Timestamp time = new Timestamp(parsedDate.getTime());
        System.out.println(dateFormat2.format(time.getTime()));

    } catch (ParseException e) {
        e.printStackTrace();
    }

}
LeoN
  • 1,590
  • 1
  • 11
  • 19
1

You are printing a timestramp. kindly change it to string like below

  String timeStamp = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss").format(time);

it will give you expected result

Chandan Sarma
  • 45
  • 2
  • 7
1

The extra "0" is for milliseconds. And to omit that you can follow below link,

Converting java date to Sql timestamp

and from there this solution, https://stackoverflow.com/a/22857062/1529092

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms

Or you can use below link to convert in different formats, How to remove milliseconds from Date Object format in Java

darshgohel
  • 382
  • 2
  • 13