-1

I am trying to convert the string to date and i want that date to be in this format 'yyyy-MM-d HH:mm:ss' and i no how to get this format in string my question is i want to get Date in above format not as string but as 'Date '?

i am doing in this way

for(int k=0;k<12;k++)//for the months
{
     //i have added if condtion for the months with 31 and 30 and 28 days
    Calendar dateFromCal = Calendar.getInstance();
    dateFromCal.setTime(date);
    dateFromCal.set(year, k, 1, 0, 0, 0);

    Calendar dateToCal = Calendar.getInstance();
    dateToCal.setTime(date);
    dateToCal.set(year, k, 31, 23, 59, 59);

    //i have set the date format as 'yyyy:MM:dd HH:mm:ss'  
    dateFrom = dateFormat.format(dateFromCal.getTime());
    dateTo = dateFormat.format(dateToCal.getTime());

    fromdate = (Date)dateFormat.parse(dateFrom);
    todate = (Date)dateFormat.parse(dateTo);

}       

by using above code i am getting the date in the following format

Sat Nov 01 00:00:00 GMT 2014

but i want the date format to be as

2014-11-01 00:00:00

NOTE:I want this result as Date not as String

Please give me solution for this Thanks....

E-Riz
  • 31,431
  • 9
  • 97
  • 134
Saleem Khan
  • 339
  • 3
  • 16
  • 1
    Why haven't you shown us the crucial declaration and initialization of `dateFormat`? – Jon Skeet Aug 13 '14 at 13:39
  • i have already done that in my code, here i haven't shown – Saleem Khan Aug 13 '14 at 13:52
  • 1
    Yes, that's the point - you haven't shown us everything that's potentially relevant. (Although in this case the problem is a fundamental misunderstanding of the `Date` type.) Please read http://tinyurl.com/stack-hints – Jon Skeet Aug 13 '14 at 14:22
  • 1
    possible duplicate of [Java string to date conversion](http://stackoverflow.com/questions/4216745/java-string-to-date-conversion) and [this](http://stackoverflow.com/q/4772425/642706) and [this](http://stackoverflow.com/q/8307417/642706) and [many others](http://stackoverflow.com/search?q=java+date+format). – Basil Bourque Aug 14 '14 at 05:51
  • For new readers to this question I strongly recommend you don’t use `SimpleDateFormat` and `Calendar`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` or `ZonedDateTime` in any case along with `DateTimeFormatter`. All are from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Aug 24 '22 at 16:54

4 Answers4

7

i want to get Date in above format not as string but as 'Date '?

You're asking for a Date in a particular format - that's like saying "I want an int in hex format." A Date doesn't have a format - it's just an instant in time. It doesn't know about a calendar system or a time zone - it's just a number of milliseconds since the Unix epoch. If you want a formatted value, that's a string.

You should probably just keep the Date as it is, and format it later on, closer to the UI.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 6
    Read carefully what @Jon is saying: a `Date` object *doesn't have a format*. A `DateFormat` object can be used to produce a String representation of a `Date` but there is no inherent format to the `Date` itself. – E-Riz Aug 13 '14 at 13:58
0

I had same problem with one API that was expecting particular format (javax.xml.datatype.XMLGregorianCalendar). In my case I solve this by the help of java 7

and

my_date.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

By doing so you can get your final result for date with 00:00:00.

ekostadinov
  • 6,880
  • 3
  • 29
  • 47
0

This is a simple method that takes care of formatting from String to Date:

                                                                                                                                 ` see code below:        
    public XMLGregorianCalendar formatToGregorianDate(String myDate) {
    //actual Date format should be "dd-MMM-yy", but SimpleDateFormat accepts only this one
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;

    try {
        //Date is accepted only without time or zone
        date = simpleDateFormat.parse(myDate.substring(0, 10));
    } catch (ParseException e) {
        System.out.println("Date can't be parsed to required format!");
        e.printStackTrace();
    }

    GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
    gregorianCalendar.setTime(date);
    XMLGregorianCalendar result = null;
    try {
        result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
        //date must be sent without time
        result.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
    } catch (DatatypeConfigurationException e) {
        System.out.println("XMLGregorianCalendar can't parse the Date format!");
        e.printStackTrace();
    }

    return result;
}`

Maybe you'll just need to adapt it for your needs, I don't know what do you need.
FYI - Note that I'm using java.util.Date. Maybe there is better logic, but this one works for sure.

Hope it helps.

ekostadinov
  • 6,880
  • 3
  • 29
  • 47
0

NOTE:I want this result as Date not as String

Short answer: It is NOT possible.

Details:

A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);

sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);

sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);

In fact, none of the standard Date-Time classes has an attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:

  • For the modern Date-Time API: java.time.format.DateTimeFormatter
  • For the legacy Date-Time API: java.text.SimpleDateFormat

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        int year = 2021;
        int month = 6;
        int hour = 23;
        int minute = 59;
        int second = 59;
        
        LocalDateTime ldt = LocalDate.of(year, month, 1)
                            .with(TemporalAdjusters.lastDayOfMonth())
                            .atTime(LocalTime.of(hour, minute, second));

        // Default format i.e. ldt#toString
        System.out.println(ldt);

        // Custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
        String formatted = dtf.format(ldt);
        System.out.println(formatted);
    }
}

Output:

2021-06-30T23:59:59
2021-06-30 23:59:59

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110