Rectangle 27 105

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes. See Tutorial by Oracle.

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 1

Do not conflate date-time values with their textual representation

myJavaSqlDate.toLocalDate()
             .format(
                 DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG )
                                  .withLocale ( Locale.UK )
             )

As others said, a date-time object has no format. Only strings generated from the object or parsed by the object have a format. But such strings are always separate and distinct from the date-time object.

The very purpose of JDBC is to mediate the differences in types between your database and Java.

The other Answers are outdated as they use the troublesome old legacy date-time classes or the venerable Joda-Time library. Both have been supplanted by the java.time classes.

If you have a java.sql.Date object in hand, convert to java.time.LocalDate by calling the new method toLocalDate added to the old class.

LocalDate ld = myJavaSqlDate.toLocalDate() ;

For JDBC drivers that comply with JDBC 4.2 and later, you can work directly with java.time types.

You seem to be interested in the date-only values. So use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

PreparedStatement::setObject
ResultSet::getObject

To generate a string in your desired format, you could specify a custom formatting pattern. But I suggest letting java.time automatically localize.

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
LocalDate ld = LocalDate.now ( ZoneId.of ( "America/Montreal" ) );  // Today's date at this moment in that zone.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.UK );
String output = ld.format ( f );

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Best way to convert Java SQL Date from yyyy-MM-dd to dd MMMM yyyy form...

java date format
Rectangle 27 25

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());

i have an string in dd/MM/yyyy format how can i convert

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 1

OffsetDateTime.parse( "2012-12-31T13:32:56.483+13:00" ).toLocalDate()

Your input string is in standard ISO 8601 format.

The java.time classes use the standard formats by default, so no need to specify a formatting pattern.

As the accepted Answer explains, you should not conflate date-time objects with strings that may textually represent their value. A java.util.Date object has no format as it has no text. Ditto for the java.time classes. You can use a java.time object to parse a string, or generate a string, but the object is distinct and separate from the string.

Parse your input string as a OffsetDateTime as it includes an offset-from-UTC though it lacks a time zone.

OffsetDateTime odt = OffsetDateTime.parse( "2012-12-31T13:32:56.483+13:00" );

If you want a date-only value, use the LocalDate class. Remember that for any given moment, the date varies around the globe by time zone. A minute after midnight is a new day in Paris while still yesterday in Montral Qubec. If you want the date from that same offset of +13:00, simply call toLocalDate.

LocalDate localDate = odt.toLocalDate();

The Question says you do not want a string, only a date object. So there you go. If you later want a string, call toString for a String to be generated in standard ISO 8601 format, 2012-12-31. For other formats, search Stack Overflow for DateTimeFormatter.

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert dateTime to date in dd/MM/yy format in java - Stack Overflow

java date datetime
Rectangle 27 4

The java.util.Date class does not have any property to hold a format.

To display the value of the Date in a custom format, call the format method on SimpleDateFormat.

System.out.println(dateInstance)

you are simply calling the toString() on the Date. That method returns the date in fixed format in String version.

If you anyhow wants the custom format with date instance then you can either create a custom class wrapping date instance

class MyDate{
  private Date date;
  //provide appropriate accessor
  //override toString() method to support required output
}
extend
Date
class MyDate extends Date{
   //override toString() method to support required output
   @Override
   public String toString(){
        //convert `this` to  String with required format with the help of `SimpleDateFormat`
   }
}

Keep it in String

I must convert it to Date type with the same format...

Date object doesn't represent the format of date

Then what would be the solution.. I need to return the format of dd/mm/yyyy of Date type. But not String type

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - can we convert String formatted date dd/mm/yyyyy to Date type i...

java date simpledateformat
Rectangle 27 3

SimpleDateFormat newDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = newDateFormat.parse("28/12/2013");
newDateFormat.applyPattern("yyyy/MM/dd")
String myDateString = newDateFormat.format(myDate);

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 2

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy h:mm a"];
NSDate *date = [dateFormat dateFromString:dateStr];
[dateFormat release];

here is the SO post

use the below statement and plz let me know if you still require help [dateFormat setDateFormat:@"dd-MM-yyyy"];

iphone - How can I convert string into date? - Stack Overflow

iphone objective-c nsstring nsdate nsdateformatter
Rectangle 27 20

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

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}

Of course, minutes are "mm", I corrected the code example.

java - How can I convert a Timestamp into either Date or DateTime obje...

java datetime date jdbc timestamp
Rectangle 27 1

An NSDate includes both date and time. No two NSDate values will be equal unless the times are identical down to the millisecond (if not finer). When you do [NSDate date] you get the exact time of "now", while if you use NSDateFormatter to convert a string to date (with no time value) then midnight is used.

If you want to see if two NSDates fall on the same day you can use NSCalendar & NSDateComponents. Or you can "cheat" and format both dates to a date string with no time value and compare the strings.

- (void) CompareDate:(NSDate*)date1 toDate:(NSDate*)date2 {
    NSDateFormatter* fmt = [NSDateFormatter new];
    [fmt setDateFormat:@"yyyyMMdd"];
    // Note that you should set the appropriate timezone if you don't want the default.
    NSString* date1Str = [fmt stringFromDate:date1];
    NSString* date2Str = [fmt stringFromDate:date2];
    switch ([date1Str compare:date2Str]) {
        case NSOrderedAscending:
            NSLog(@"Date 1 is earlier");
            break;
        case NSOrderedSame:
            NSLog(@"Dates are equal");
            break;
        case NSOrderedDescending:
            NSLog(@"Date 2 is earlier");
            break;
    }
}

ios - How can I compare "today" (NSDate) to a formatted string date (d...

ios objective-c date compare nsdate
Rectangle 27 9

String DATE_FORMAT = "yyyy/MM/dd";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    System.out.println("Formated Date " + sdf.format(date));
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaSimpleDateFormatExample {
    public static void main(String args[]) {
        // Create Date object.
        Date date = new Date();
        // Specify the desired date format
        String DATE_FORMAT = "yyyy/MM/dd";
        // Create object of SimpleDateFormat and pass the desired date format.
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        /*
         * Use format method of SimpleDateFormat class to format the date.
         */
        System.out.println("Today is " + sdf.format(date));
    }
}

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 279

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.date(from: /* your_date_string */)

Found the solution just need to set "yyyy-MM-dd hh:mm:ss.SSSSxxx" this date format

I have a date string like this "2014-07-15 06:55:14-0400" and i tried using yyyy-MM-dd hh:mm:ssZZZ . But I'm not able to get the date object out of the string.

@Prem, if you see the output is "2014-07-15 10:55:14 +0000" that will be correct. As from NSDate description, output of date would be calculated with difference(here, GMT -4 hours). If you want to get the difference between GMT and UTC, which is -0400 check this reference

@ lmiguelvargasf, I think that would be yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. I assumed Z is just a character here. Remember, Z has a special meaning too. If you want Z to specify as basic hms than the format would be yyyy-MM-dd'T'HH:mm:ss.SSSZ.

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 276

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.date(from: /* your_date_string */)

Found the solution just need to set "yyyy-MM-dd hh:mm:ss.SSSSxxx" this date format

I have a date string like this "2014-07-15 06:55:14-0400" and i tried using yyyy-MM-dd hh:mm:ssZZZ . But I'm not able to get the date object out of the string.

@Prem, if you see the output is "2014-07-15 10:55:14 +0000" that will be correct. As from NSDate description, output of date would be calculated with difference(here, GMT -4 hours). If you want to get the difference between GMT and UTC, which is -0400 check this reference

@ lmiguelvargasf, I think that would be yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. I assumed Z is just a character here. Remember, Z has a special meaning too. If you want Z to specify as basic hms than the format would be yyyy-MM-dd'T'HH:mm:ss.SSSZ.

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 2

final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");

String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);

1 well, not that new anymore, Java 9 should be released soon.

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 2

Date prints a format based on the Locale. It doesn't "remember" the format you gave it want you constructed it. Only Strings have a particular format, so if you need that, keep it as a String.

Hi Peter, I'm inserting the same data member into the database with Date as the column type.So i should have to convert to date only...

java - can we convert String formatted date dd/mm/yyyyy to Date type i...

java date simpledateformat
Rectangle 27 45

func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}
func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 44

func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}
func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 6

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

Parse the input string as a date-time object, then generate a new String object in the desired format.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

By the way, consider using standard ISO 8601 formats for strings representing date-time values.

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

  • Part of the standard Java API with a bundled implementation.
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.

//  2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
localDate: 2010-08-12
newDateString: 2010/08/12

How can I change the date format in Java? - Stack Overflow

java date
Rectangle 27 59

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

I can do it with this code.

The code is not right. It outputs Some "Jan 15, 2014, 12:00 AM"

using dd instead of DD should help fix the "always January" issue.

The correct version is, yyyy-MM-dd, otherwise, the parsed date is stuck in January - I updated the answer to reflect the change.

What if I want to pass the current date as string. Will this work?

@Zorayr , Kittisak : I am getting the out put, Optional(2014-07-14 18:30:00 +0000) that means, one day is decremented. How can I fix this ?

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 59

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

I can do it with this code.

The code is not right. It outputs Some "Jan 15, 2014, 12:00 AM"

using dd instead of DD should help fix the "always January" issue.

The correct version is, yyyy-MM-dd, otherwise, the parsed date is stuck in January - I updated the answer to reflect the change.

What if I want to pass the current date as string. Will this work?

@Zorayr , Kittisak : I am getting the out put, Optional(2014-07-14 18:30:00 +0000) that means, one day is decremented. How can I fix this ?

ios - How can I convert string date to NSDate? - Stack Overflow

ios string swift nsdate
Rectangle 27 4

NSString *string=@"03-05-2014";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:string];

This code will result in 2 memory leaks. dateFormatter must be released and there is no need to allocate an NSDate to dateFromStringdateFromString: returns an autoreleased instance.

ijust gave sample.. not a perfect code.

iphone - How can I convert string into date? - Stack Overflow

iphone objective-c nsstring nsdate nsdateformatter