Going from MM/DD/YYYY to DD-MMM-YYYY in java - java

Is there a method in Java that I can use to convert MM/DD/YYYY to DD-MMM-YYYY?
For example: 05/01/1999 to 01-MAY-99

Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Here's some code:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
Date date = format1.parse("05/01/1999");
System.out.println(format2.format(date));
Output:
01-May-99

java.time
You should use java.time classes with Java 8 and later. To use java.time, add:
import java.time.* ;
Below is an example, how you can format date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));

Try this,
Date currDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = dateFormat.format(currDate);
System.out.println("strCurrDate->"+strCurrDate);

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate

Try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
String currentData = sdf.format(new Date());

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*.
A Date-Time parsing/formatting type is Locale-sensitive
A Date-Time parsing/formatting type (e.g. DateTimeFormatter) is Locale-sensitive i.e. the same letters will produce the text in different Locales .e.g. MMM is used for the three-letter abbreviation of month name and it can be different words in different Locales. In the absence of the Locale parameter, it will use the JVM's Locale. Therefore, never forget to use a Date-Time parsing/formatting type without the Locale parameter. Learn more about it from Never use SimpleDateFormat or DateTimeFormatter without a Locale.
You need two instances of DateTimeFormatter - one to parse the input string and another to format the output string, as per required patterns.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String strDate = "05/01/1999";
LocalDate date = LocalDate.parse(strDate, dtfInput);
// The default string i.e. the value returned by LocalDate#toString
System.out.println(date);
DateTimeFormatter dtfOutputEng = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ENGLISH);
String formattedEng = dtfOutputEng.format(date);
System.out.println(formattedEng);
DateTimeFormatter dtfOutputFr = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.FRENCH);
String formattedFr = dtfOutputFr.format(date);
System.out.println(formattedFr);
}
}
Output:
1999-05-01
01-May-1999
01-mai-1999
ONLINE DEMO
Some other important notes:
Instead of Y (week-based-year), you need to use y (year-of-era) and instead of D (day-of-year), you need to use d (day-of-month). Check the documentation to learn more about it.
Here, you can use y instead of u but I prefer u to y.
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.

Below should work.
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date oldDate = df.parse(df.format(date)); //this date is your old date object

formatter = new SimpleDateFormat("dd-MMM-yy");

Related

Unparseable MMM-dd-yyyy

I will be direct with my question. I am wondering why I can't parse a fromat MMM-dd-yyyy into yyyy-MM-dd (java.sql.Date format)? Any suggestion on how I am going to convert a String into a format of (yyyy-MM-dd)?
Here is the code:
public DeadlineAction(String deadline){
putValue(NAME, deadline);
deadLine = deadline;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd");
try {
finalDate = (Date) formatter.parse(deadLine);
}catch(ParseException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Thank you
Basically, you can't parse a String in the format of MMM-dd-yyyy using the format of yyyy MM dd, it just doesn't make sense, you need one formatter to parse the value and another to format itm for example
SimpleDateFormat to = new SimpleDateFormat("yyyy MM dd");
SimpleDateFormat from = new SimpleDateFormat("MMM-dd-yyyy");
Date date = from.parse(deadLine);
String result = to.format(date)
The question that needs to be asked is, why you would bother. If your intention is to put this value into the database, you should be creating an instance of java.sql.Date (from the java.util.Date) and using PreparedStatement#setDate to apply it to your query, then letting the JDBC driver deal with it
The answer by MadProgrammer is correct. You must define a formatting pattern to fit the format of your input data string.
You could avoid the problem in the first place by using the java.time framework.
java.time
The java.time framework is built into Java 8 and later (also back-ported to Java 6 & 7 and to Android). These classes supplant the old troublesome legacy date-time classes (java.util.Date/.Calendar).
ISO 8601
Your input strings are apparent is standard ISO 8601 format, YYYY-MM-DD such as 2016-01-23.
The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern.
Parsing string
For a date-only value without time-of-day and without time zone, use LocalDate class.
LocalDate localDate = LocalDate.parse( "2016-01-23" );
Generating string
To generate a string representing that LocalDate object’s value, just call toString to get a string in ISO 8601 format.
String output = localDate.toString(); // 2016-01-23
For other formats, use the java.time.format package. Usually best to let java.time automatically localize to the user’s human language and cultural norms defined by a Locale.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
Locale locale = Locale.CANADA_FRENCH;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Or you can specify your own particular pattern. Note that you should still specify a Locale to determine aspects such as the name-of-month or name-of-day. Here is a demo of the pattern that seems to be asked in the Question (not sure as Question is unclear).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM-dd-yyyy" );
Locale locale = Locale.US;
formatter = formatter.withLocale( locale );
String output = localDate.format( formatter );
Try something like:
try {
final String deadLine = "Oct-12-2006";
SimpleDateFormat formatter = new SimpleDateFormat("MMM-dd-yyyy");//define formatter for yout date time
Date finalDate = formatter.parse(deadLine);//parse your string as Date
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");// define your desired format
System.out.println(formatter2.format(finalDate));//format the string to your desired date format
} catch (Exception e) {
//handle
}
Your example is not unparseable. I removed the dashes from MMM-dd-yyyy to MMM dd yyyy. You can put them back if needed. I also removed the any extra code to make the solution clear.
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public DeadlineAction(String deadline){
//if deadline has format similar to "December 19 2011"
try {
finalDate = new java.sql.Date(
((java.util.Date) new SimpleDateFormat("MMM dd yyyy").parse(deadline)).getTime());
}catch(ParseException e) {
//Your exception code
e.printStackTrace();
}
}
This works for almost every conversion to sqlDate. Just change SimpleDateFormat("MMM dd yyyy") to what you need it to be.
Example: new SimpleDateFormat("MMM-yyyy-dd").parse("NOVEMBER-2012-30")

Date(String) parse error in Java

I am using the following lines of code to parse a String as a Date:
String displayBirthday;
...
java.util.Date ss1=new Date(displayBirthday);
SimpleDateFormat formatter5=new SimpleDateFormat("yyyy-MM-dd");
displayBirthday = formatter5.format(ss1);
li.add(displayBirthday);
It works fine for many dates, but when I want to parse a date like: 0001-03-10
It gives me the following error:
java.lang.IllegalArgumentException: Parse error: 0001-03-10
I am using a prefix of 0001 for dates which dont have a year as an internal representation. How to overcome this?
Date(java.lang.String)' is deprecated , just use SimpleDateFormat
Just like follows
SimpleDateFormat formatter5=new SimpleDateFormat("yyyy-MM-dd");
String displayBirthday = formatter5.format(formatter5.parse("0001-03-10"));
System.out.println(displayBirthday);
Out put:
0001-03-10
java.time
In Mar 2014 (months before the question was posted), the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Using java.time, the modern date-time API:
You do not need a DateTimeFormatter: java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date string, 0001-03-10 which can be parsed directly into a LocalDate instance which contains just date units.
Demo:
import java.time.LocalDate;
class Main {
public static void main(String args[]) {
String strDateTime = "0001-03-10";
LocalDate date = LocalDate.parse(strDateTime);
System.out.println(date);
}
}
Output:
0001-03-10
ONLINE DEMO
I am using a prefix of 0001 for dates which dont have a year as an
internal representation. How to overcome this?
As suggested by Ole V.V., a MonthDay is probably a good answer to it. Note that the default pattern used by MonthDay#parse is --MM-dd. If your string is not in this format, you can build a custom DateTimeFormatter.
An alternative to parsing to MonthDay is building a DateTimeFormatter with default year which will allow your string to be parsed directly into a LocalDate.
Demo:
class Main {
public static void main(String args[]) {
// If your string is in --MM-dd format
MonthDay monthDay = MonthDay.parse("--03-10");
// If you want the current year, replace 1 with Year.now().getValue()
LocalDate date = monthDay.atYear(1);
System.out.println(date);
// If your string is in MM-dd format
DateTimeFormatter monthDayFormatter = DateTimeFormatter.ofPattern("MM-dd", Locale.ENGLISH);
monthDay = MonthDay.parse("03-10", monthDayFormatter);
// If you want the current year, replace 1 with Year.now().getValue()
date = monthDay.atYear(1);
System.out.println(date);
// An alternative solution
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("MM-dd")
// If you want the current year, replace 1 with Year.now().getValue()
.parseDefaulting(ChronoField.YEAR, 1)
.toFormatter(Locale.ENGLISH);
date = LocalDate.parse("03-10", dtf);
System.out.println(date);
}
}
Output:
0001-03-10
0001-03-10
0001-03-10
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

Localized date format in Java

I have a timestamp in millis and want to format it indicating day, month, year and the hour with minutes precission.
I know I can specify the format like this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm");
String formatted = simpleDateFormat.format(900000)
But I'd like the format to be localized with the user's locale. I've also tried
DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
DATE_FORMAT.format(new Date());
But it does not show the hour. How can I do it?
Is using joda time (http://joda-time.sourceforge.net/) out of the question? If not, then I would wholeheartedly recommend using this wonderful library instead of the cumbersome Java API.
If not, you could use DateFormat.getDateTimeInstance(int, int, Locale)
The first int is the style for hour, the other is the style for time, so try using:
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
String formattedDate = f.format(new Date());
System.out.println("Date: " + formattedDate);
See if this suits you.
Output for Locale.GERMANY:
Date: 25.07.13 10:57
Output for Locale.US:
Date: 7/25/13 10:57 AM
But it does not show the hour. How can I do it?
You have to call DateFormat.getDateTimeInstance(int, int, Locale)
DateFormat.getDateInstance(int, Locale) => Gets the date formatter with the given formatting style for the given locale.
While
DateFormat.getDateTimeInstance(int, int, Locale) => Gets the date/time formatter with the given formatting styles for the given locale.
Try some thing like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
String formatted = simpleDateFormat.format(900000);
System.out.println(simpleDateFormat.parse(formatted));
You can use method getDateTimeInstance, of DateFormat. Here the getDateTimeInstance method takes 3 arguments
the style of Date field
the style of time field
the Locale using which pattern is auto extracted
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
System.out.println(DATE_FORMAT.format(d));
DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.FRENCH);
System.out.println(DATE_FORMAT.format(d));
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
You can use DateTimeFormatter.ofLocalizedDateTime to obtain a locale-specific date format for the ISO chronology.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfLocalized = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
// Test
LocalDateTime date = LocalDateTime.now();
System.out.println(dtfLocalized.withLocale(Locale.US).format(date));
System.out.println(dtfLocalized.withLocale(Locale.UK).format(date));
System.out.println(dtfLocalized.withLocale(Locale.CHINESE).format(date));
System.out.println(dtfLocalized.withLocale(Locale.GERMAN).format(date));
System.out.println(dtfLocalized.withLocale(Locale.forLanguageTag("tr")).format(date));
System.out.println(dtfLocalized.withLocale(Locale.getDefault()).format(date));
}
}
Output:
5/8/21, 10:49 PM
08/05/2021, 22:49
2021/5/8 下午10:49
08.05.21, 22:49
8.05.2021 22:49
08/05/2021, 22:49
Learn more about the 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.
Using Joda-Time you could detect the system setting and use different time format:
String format;
if (DateFormat.is24HourFormat(context)) {
format = "MM/dd/yy, hh:mm";
}
else {
format = "MM/dd/yy, h:mm aa";
}
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
formatter.print(new DateTime());

How to convert date in to yyyy-MM-dd Format?

Sat Dec 01 00:00:00 GMT 2012
I have to convert above date into below format
2012-12-01
How can i?
i have tried with following method but its not working
public Date ConvertDate(Date date){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(date);
String result = s;
try {
date=df.parse(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
String s;
Format formatter;
Date date = new Date();
// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
Joda-Time
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 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.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.
The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time.
You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.
Moreover, most of the getter methods in Date are deprecated.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.
Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
The date-time API of java.util 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.
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.

How to properly format the date?

The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?
String date = "2010-08-25";
String time = "00:00";
Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?
private static Date date(final String date,final String time) {
final Calendar calendar = Calendar.getInstance();
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String[] hm = time.split(":");
int hour = Integer.parseInt(hm[0]);
int minute = Integer.parseInt(hm[1]);
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d = calendar.getTime();
String dateString= dateFormat.format(d);
Date result = null;
try {
result = (Date)dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
What's wrong in this code?
You seem to be expecting the returned Date object to know about the format you've parsed it from - it doesn't. It's just an instant in time. When you want a date in a particular format, you use SimpleDateFormat.format, it's as simple as that. (Well, or you use a better library such as Joda Time.)
Think of the Date value as being like an int - an int is just a number; you don't have "an int in hex" or "an int in decimal"... you make that decision when you want to format it. The same is true with Date.
(Likewise a Date isn't associated with a specific calendar, time zone or locale. It's just an instant in time.)
How did you print out the return result? If you simply use System.out.println(date("2010-08-25", "00:00") then you might get Sat Sep 8 00:00 PDT 2010 depending on your current date time format setting in your running machine. But well what you can do is:
Date d = date("2010-08-25", "00:00");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d));
Just curious why do you bother with this whole process as you can simple get the result by concatenate your initial date and time string.
just use SimpleDateFormat class
See
date formatting java simpledateformat
The standard library does not support a formatted Date-Time object.
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT
2010". But I expected to get the date in the following format
"yyyy-MM-dd HH:mm".
The standard Date-Time classes do not have any 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
About java.util.Date:
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). 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(); // In your case, it will be Date date = date("2010-08-25", "00:00");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
// sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); // For a timezone-specific value
String strDate = sdf.format(date);
System.out.println(strDate);
Your function, Date date(String, String) is error-prone.
You can simply combine the date and time string with a separator and then use SimpleDateFormat to parse the combined string e.g. you can combine them with a whitespace character as the separator to use the same SimpleDateFormat shown above.
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
Note that using a separator is not a mandatory requirement e.g. you can do it as sdf.parse(date + time) but for this, you need to change the format of sdf to yyyy-MM-ddHH:mm which, although correct, may look confusing.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Date date = date("2010-08-25", "00:00");
String strDate = sdf.format(date);
System.out.println(strDate);
}
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
}
Output:
2010-08-25 00:00
ONLINE DEMO
Switch to java.time API.
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*.
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.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = localDateTime("2010-08-25", "00:00");
// Default format i.e. the value of ldt.toString()
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ENGLISH);
String strDate = dtf.format(ldt);
System.out.println(strDate);
}
private static LocalDateTime localDateTime(final String date, final String time) {
return LocalDateTime.of(LocalDate.parse(date), LocalTime.parse(time));
}
}
Output:
2010-08-25T00:00
2010-08-25 00:00
ONLINE DEMO
You must have noticed that I have not used DateTimeFormatter for parsing the String date and String time. It is because your date and time strings conform to the ISO 8601 standards. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
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.
I'm surprise you are getting different date outputs on the different computers. In theory, SimpleDateFormat pattern "H" is supposed to output the date in a 24h format. Do you get 11:45pm or 11:45am?
Although it should not affect the result, SimpleDateFormat and Calendar are Locale dependent, so you can try to specify the exact locale that you want to use (Locale.US) and see if that makes any difference.
As a final suggestion, if you want, you can also try to use the Joda-Time library (DateTime) to do the date manipulation instead. It makes it significantly easier working with date objects.
DateTime date = new DateTime( 1991, 10, 13, 23, 39, 0);
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm").format( date.toDate());
DateTime newDate = DateTime.parse( dateString, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));

Categories