By amit4444


2011-01-23 05:09:48 8 Comments

I've a String representing a date.

String date_s = "2011-01-18 00:00:00.0";

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?


Okay, based on the answers I retrieved below, here's something I've tried:

String date_s = " 2011-01-18 00:00:00.0"; 
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date date = dt.parse(date_s); 
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

16 comments

@Neeraj Gahlawat 2017-02-16 05:48:27

public class SystemDateTest {

    String stringDate;

    public static void main(String[] args) {
        SystemDateTest systemDateTest = new SystemDateTest();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
        systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
        System.out.println(systemDateTest.getStringDate());
    }

    public Date getDate() {
        return new Date();
    }

    public String getStringDate() {
        return stringDate;
    }

    public void setStringDate(String stringDate) {
        this.stringDate = stringDate;
    }
}

@Kursad Gulseven 2017-02-16 06:09:08

Please add some information to your answer(s) to explain your code.

@Neeraj Gahlawat 2017-02-23 09:47:06

there is a method name getDate() by which u can get date obj after that apply SimpleDateFormat so that you can convert date according to your format which is defined in SimpleDateFormat constructor and set in StringDate method you can make it cached

@BalusC 2011-01-23 05:20:56

Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

Use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

Or, when you're not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

See also:


Update: as per your failed attempt: the patterns are case sensitive. Read the java.text.SimpleDateFormat javadoc what the individual parts stands for. So stands for example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.

@crm 2014-06-05 10:20:38

What if you want the date to look like "Monday 1st September 2012"?

@BalusC 2014-06-05 11:19:57

@crm: Just click the javadoc link, figure the necessary pattern characters there and alter the pattern accordingly.

@Igor 2016-11-14 11:06:10

I have error with using HH instead hh.

@dev 2014-06-26 06:27:49

Formatting are CASE-SENSITIVE so USE MM for month not mm (this is for minute) and yyyy For Reference you can use following cheatsheet.

G   Era designator  Text    AD
y   Year    Year    1996; 96
Y   Week year   Year    2009; 09
M   Month in year   Month   July; Jul; 07
w   Week in year    Number  27
W   Week in month   Number  2
D   Day in year Number  189
d   Day in month    Number  10
F   Day of week in month    Number  2
E   Day name in week    Text    Tuesday; Tue
u   Day number of week (1 = Monday, ..., 7 = Sunday)    Number  1
a   Am/pm marker    Text    PM
H   Hour in day (0-23)  Number  0
k   Hour in day (1-24)  Number  24
K   Hour in am/pm (0-11)    Number  0
h   Hour in am/pm (1-12)    Number  12
m   Minute in hour  Number  30
s   Second in minute    Number  55
S   Millisecond Number  978
z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00
Z   Time zone   RFC 822 time zone   -0800
X   Time zone   ISO 8601 time zone  -08; -0800; -08:00

Examples:

"yyyy.MM.dd G 'at' HH:mm:ss z"  2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"  Wed, Jul 4, '01
"h:mm a"    12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"  02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"    Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"   2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"   2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"  2001-W27-3

@a fair player 2014-08-06 15:54:57

"yyyy-MM-dd'T'HH:mm:ss.SSSZ" should be "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

@dev 2014-08-14 06:26:43

no if u put Z in single quote it will give Z as output but without it it will give Timezone. eg. 2014-08-14T01:24:57.236Z and from without it 2014-08-14T01:24:57.236-0530 --> I tried on jdk1.7

@Stefano Mtangoo 2014-12-12 08:53:34

"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM Note extra M in month. Four not five!

@dev 2014-12-12 09:03:06

if it's 4 letters or more, then the full form is used. so you can use 4 times m or even 5 times m its same

@XenoRo 2015-12-03 12:19:06

This is pretty much a Copy-Paste of the docs. No extra explanations are being provided, and there is no link to the docs where more info could be acquired if needed. -1. (Here's the link btw)

@Bhavin Shah 2016-02-09 09:00:38

Very useful. Thank you.

@viper 2017-02-13 05:14:20

This is the most satisfying answer that I have found on using date formatter on java. Thank you very much

@ban-geoengineering 2017-03-15 14:36:08

In Android, MMMMM didn't work for me, but MMMM did.

@Alberto Cerqueira 2017-11-24 14:14:43

Thanks, very nice! I needed use yyyy-MM-dd'T'HH:mm:ssXXX

@89n3ur0n 2014-05-10 11:24:20

Why not simply use this

Date convertToDate(String receivedDate) throws ParseException{
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = formatter.parse(receivedDate);
        return date;
    }

Also, this is the other way :

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();

or

Date requiredDate = df.format(new Date());

Cheers!

@Basil Bourque 2014-06-26 06:37:06

Why not use this? Because (a) it ignores the issue of time zone. Determining the date depends on the time zone. This code depends on the JVM's default time zone. So, results may vary inadvertently. And (b) because the java.util.Date and SimpleDateFormat classes are notoriously troublesome and should be avoided.

@delive 2018-01-30 12:17:38

always return strin, Date requiredDate = df.format(new Date());

@Touchstone 2015-03-13 10:39:10

Please refer "Date and Time Patterns" here. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateConversionExample{

  public static void main(String arg[]){

    try{

    SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

    Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");


    SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(targetDateFormat.format(date));

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

}

@Ran Adler 2014-08-27 06:09:48

You could try java 8 new date, more information can be found on the oracle documentation.

Or you can try the old one

public static Date getDateFromString(String format, String dateStr) {

        DateFormat formatter = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = (Date) formatter.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    public static String getDate(Date date, String dateFormat) {
        DateFormat formatter = new SimpleDateFormat(dateFormat);
        return formatter.format(date);
    }

@Vadzim 2017-04-17 17:49:27

This code is not related to Java 8 Time API in any single part.

@Vitalii Fedorenko 2014-04-20 15:42:57

Using the java.time package in Java 8 and later:

String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm:ss.S")
    .parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);

@chŝdk 2014-05-26 16:40:58

You can just use:

Date yourDate = new Date();

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);

It works perfectly!

@Fathah Rehman P 2014-01-07 02:41:14

try
 {
    String date_s = "2011-01-18 00:00:00.0";
    SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date tempDate=simpledateformat.parse(date_s);
    SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");           
    System.out.println("Output date is = "+outputDateFormat.format(tempDate));
  } catch (ParseException ex) 
  {
        System.out.println("Parse Exception");
  }

@Basil Bourque 2013-11-30 05:07:27

Other answers are correct, basically you had the wrong number of "y" characters in your pattern.

Time Zone

One more problem though… You did not address time zones. If you intended UTC, then you should have said so. If not, the answers are not complete. If all you want is the date portion without the time, then no issue. But if you do further work that may involve time, then you should be specifying a time zone.

Joda-Time

Here is the same kind of code but using the third-party open-source Joda-Time 2.3 library

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

When run…

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z

@Martin 2013-10-12 09:08:18

You can also use substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

If you want a space in front of the date, use

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

@Pankaj Sharma 2013-09-23 06:45:52

remove one y form SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd"); should be SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

@user2632575 2013-07-30 04:11:34

private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(value instanceof Date) {
        value = dataFormat.format(value);
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};

@Eren 2012-05-26 14:55:45

   String str = "2000-12-12";
   Date dt = null;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    try 
    {
         dt = formatter.parse(str);
    }
    catch (Exception e)
    {
    }

    JOptionPane.showMessageDialog(null, formatter.format(dt));

@Hovercraft Full Of Eels 2011-01-23 05:12:18

The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.

Addendum: "mm" in the format String is not the same as "MM". Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy. e.g.,:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}

@amit4444 2011-01-23 05:14:27

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class formateDate { /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // TODO Auto-generated method stub String date_s=" 2011-01-18 00:00:00.0"; SimpleDateFormat dt= new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); Date date=dt.parse(date_s); SimpleDateFormat dt1= new SimpleDateFormat("yyyyy-mm-dd"); System.out.println( dt1.format(date)); } } i want out put should be "2011-01-18" but out put is 02011-00-1

@Hovercraft Full Of Eels 2011-01-23 05:15:47

Post any code you have as an addition to the original question (indented four spaces). This way it will retain its formatting and we can then read it.

@Hovercraft Full Of Eels 2011-01-23 05:19:34

See edit to my answer above. You're using "mm" in your format String where you should be using "MM"

@Andre Holzner 2016-04-07 11:36:24

hh will give you the hour in the range 1-12, you'll need to use a in addition to print/parse AM or PM. To print/parse the hour in the range 0-23, use HH.

@Bryan 2011-01-23 05:17:46

[edited to include BalusC's corrections] The SimpleDateFormat class should do the trick:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

@BalusC 2011-01-23 05:27:23

DD stands for "day in year", not "day in month". hh stands for "hour in am/pm (1-12)", not "hour in day (0-23)".

Related Questions

Sponsored Content

78 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

75 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

32 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

58 Answered Questions

[SOLVED] What is the difference between String and string in C#?

35 Answered Questions

[SOLVED] Where can I find documentation on formatting a date in JavaScript?

14 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

44 Answered Questions

[SOLVED] How to format a JavaScript date

58 Answered Questions

[SOLVED] Read/convert an InputStream to a String

17 Answered Questions

[SOLVED] Why is char[] preferred over String for passwords?

48 Answered Questions

Sponsored Content