convert string to date in java in format 2012-07-27 - java

i have the input string as 2012-07-27 and i want the output as date but with the same format like 2012-07-27
my code is
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
my output is
Fri Jul 27 00:00:00 IST 2012
but i want to return the date object like like 2012-07-26 23:59:59 instead of a string any help please
any help is very thank full

You can use your same SimpleDateFormat you used to parse the date, to format the date into a string.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = formatter.parse("2012-07-27");
System.out.println(date1); // prints Fri Jul 27 00:00:00 IST 2012
System.out.println(formatter.format(date1)); // prints 2012-07-26

First, I think it's important to note that System.out.println implicitly invokes the toString method of its argument. The argument must be an Object or a subclass of it. And Date is a subclass of Object. That being said, take a look at the 1.7 Date#toString implementation,
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
The string representation of a Date object is specified as EEE MMM dd HH:mm:ss zzz yyyy. This is exactly what you're seeing.
If you want to display a Date object in a different format, use the SimpleDateFormat class. Its sole purpose is to add flexibility to the way a Date object is represented as a string.
Also...
One possible, albeit ridiculous workaround would be to create your own wrapper class,
public class MyDate{
private final Date d;
private final SimpleDateFormat sdf;
public(Date d, SimpleDateFormat sdf){
this.d = d;
this.sdf = sdf;
}
// not recommended...should only be used for debugging purposes
#Override
public String toString(){
return sdf.format(d);
}
}

You must use another SimpleDateFormat with the desired output format (format())

You can get a String representation for a date using the same SimpleDateFormat. The format method does this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2012-07-27");
System.out.println(sdf.format(date1);

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("2012-07-27");
System.out.println(dateFormat.format(date));

There is no "format" property in java.util.Date. A Date instance is rather a simple object representing a moment in time (effectively, it's state is only defined by a unix timestamp it stores internally).
As others noted, use (for example) a SimpleDateFormat to print a Date instance as into a string.

tl;dr
LocalDate.parse( "2012-07-27" )
.toString()
2012-07-27
Details
The modern way is with the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Standard format
Your input string format happens to comply with the ISO 8601 standard. 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 at all.
LocalDate ld = LocalDate.parse( "2012-07-27" );
Do not conflate date-time objects with Strings representing their value. A date-time class/object can parse a string and generate a string, but the String is always a separate and distinct object.
String output = ld.toString();
2012-07-27
Custom format
If your input is non-standard, define a DateTimeFormatter to match.
String input = "20-12-2005" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2012-07-27
About java.time
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.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.

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")

how to check if one date is after another in java?

I am taking in two dates as command line arguments and want to check if the first one is after the second date. the format of the date it "dd/MM/yyy".
Example: java dateCheck 01/01/2014 15/03/2014
also i will need to check if a third date hardcoded into the program is before the second date.
try {
System.out.println("Enter first date : (dd/MM/yyyy)");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse(bufferRead.readLine());
System.out.println("Enter second date : (dd/MM/yyyy)");
Date date2 = sdf.parse(bufferRead.readLine());
System.out.println(date1 + "\n" + date2);
if (date1.after(date2)) {
System.out.println("Date1 is after Date2");
} else {
System.out.println("Date2 is after Date1");
}
} catch (IOException e) {
e.printStackTrace();
}
To compare two dates :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
Date firstDate = sdf.parse("01/01/2014");
Date secondDate = sdf.parse("15/03/2014");
if(firstDate.before(secondDate)){
System.out.println("firstDate < secondDate");
}
else if(firstDate.after(secondDate)){
System.out.println("firstDate > secondDate");
}
else if(firstDate.equals(secondDate)){
System.out.println("firstDate = secondDate");
}
tl;dr
LocalDate ld1 = LocalDate.parse( "01/01/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld2 = LocalDate.parse( "15/03/2014" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ;
LocalDate ld3 = LocalDate.of( 2014 , Month.JULY , 1 ) ;
Boolean isFirstDateBeforeSecondDate = ld1.isBefore( ld2 ) ;
Boolean isThirdDateBeforeSecondDate = ld3.isBefore( ld2 ) ;
Boolean result = ( isFirstDateBeforeSecondDate && isThirdDateBeforeSecondDate ) ;
return result ;
Using java.time
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match your input strings using the DateTimeFormatter class.
String input = "15/03/2014" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( input , f );
ld.toString(): 2014-03-15
To specify a fixed date, pass year, month, and dayOfMonth. For the month, you may specify a number, sanely numbered 1-12 for January-December (unlike the crazy 0-11 in the legacy classes!). Or you may choose to use the Month enum objects.
LocalDate firstOf2014 = LocalDate.of( 2014 , Month.JANUARY , 1 );
Compare using isBefore, isEqual, or isAfter methods.
Boolean isInputDateBeforeFixedDate = ld.isBefore( firstOf2014 ) ;
isInputDateBeforeFixedDate.toString(): false
ISO 8601
If possible, replace your particular date string format with the standard ISO 8601 format. That standard defines many useful practical unambiguous string formats for date-time values.
The java.time classes use the standard formats by default when parsing/generating strings. You can see examples in the code above. For a date-only value, the standard format is YYYY-MM-DD.
About java.time
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
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.
Use SimpleDateFormat to convert a string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2017");
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
To read a date and check before:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
try {
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
if(date1.before(date2)) {
// do something
}
} catch(ParseException e) {
// the format of the read dates is not the expected one
}

Convert java.util.Date to String

I want to convert a java.util.Date object to a String in Java.
The format is 2010-05-30 22:15:52
Convert a Date to a String using DateFormat#format method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
tl;dr
myUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014-11-14 14:05:09
java.time
The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.
First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Conversions to/from java.time are performed by new methods added to the old classes.
Instant instant = myUtilDate.toInstant();
Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.
String output = instant.toString();
2014-11-14T14:05:09Z
For other formats, you need to transform your Instant into the more flexible OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
See that code run live at IdeOne.com.
To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.
Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.
To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
To generate a formatted String, do the same as above but replace odt with zdt.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
Apply that formatter by passing the instance.
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.
Slightly more repetitive but needs just one statement.
This may be handy in some cases.
Why don't you use Joda (org.joda.time.DateTime)?
It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
It looks like you are looking for SimpleDateFormat.
Format: yyyy-MM-dd kk:mm:ss
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
public static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString.
Here are examples of using new Java 8 Time API to format legacy java.util.Date:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).
List of predefined fomatters and pattern notation reference.
Credits:
How to parse/format dates with LocalDateTime? (Java 8)
Java8 java.util.Date conversion to java.time.ZonedDateTime
Format Instant to String
What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh
- HH refers to 24h time format
- hh refers to 12h time format
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
From Convert Date to String in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

Going from MM/DD/YYYY to DD-MMM-YYYY in 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");

how to convert string into time format and add two hours [duplicate]

This question already has answers here:
How to add time to the current time?
(3 answers)
Closed 1 year ago.
I have the following requirement in the project.
I have a input field by name startDate and user enters in the format YYYY-MM-DD HH:MM:SS.
I need to add two hours for the user input in the startDate field. how can i do it.
Thanks in advance
You can use SimpleDateFormat to convert the String to Date. And after that you have two options,
Make a Calendar object and and then use that to add two hours, or
get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Calendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(Calendar.HOUR, 2);
Date d2 = gc.getTime();
Or,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// replace with your start date string
Date d = df.parse("2008-04-16 00:05:05");
Long time = d.getTime();
time +=(2*60*60*1000);
Date d2 = new Date(time);
Have a look to these tutorials.
SimpleDateFormat Tutorial
Calendar Tutorial
Being a fan of the Joda Time library, here's how you can do it that way using a Joda DateTime:
import org.joda.time.format.*;
import org.joda.time.*;
...
String dateString = "2009-04-17 10:41:33";
// parse the string
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatter.parseDateTime(dateString);
// add two hours
dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants
System.out.println(dateTime);
If you still need to use java.util.Date objects before/after this conversion, the Joda DateTime API provides some easy toDate() and toCalendar() methods for easy translation.
The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.
Try this one, I test it, working fine
Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime()); // Output : Wed Jul 25 14:00:00 IST 2012
If you want to convert in your input type than add this code also
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str); // Output : 2012-07-25 14:00:00
Use the SimpleDateFormat class parse() method. This method will return a Date object. You can then create a Calendar object for this Date and add 2 hours to it.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.
//the parsed time zone offset:
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromDateTimeObj = "2011-01-03T12:00:00.000-0800";
DateTime fromDatetime = dateFormat.withOffsetParsed().parseDateTime(fromDateTimeObj);
Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=hour;
this.min=min;
this.sec=sec;
}
demo add(demo d2)//demo because we are returning object
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
return obj;//Returning object and later on it gets allocated to demo d3
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(2, 5, 10);
d2.input(3, 3, 3);
demo d3=d1.add(d2);//Note another object is created
d3.display();
}
}
Modified Time Addition Program
class demo
{private int hour,min,sec;
void input(int hour,int min,int sec)
{this.hour=(hour>12&&hour<24)?(hour-12):hour;
this.min=(min>60)?0:min;
this.sec=(sec>60)?0:sec;
}
demo add(demo d2)
{ demo obj=new demo();
obj.hour=hour+d2.hour;
obj.min=min+d2.min;
obj.sec=sec+d2.sec;
if(obj.sec>60)
{obj.sec-=60;
obj.min++;
}
if(obj.min>60)
{ obj.min-=60;
obj.hour++;
}
return obj;
}
void display()
{
System.out.println(hour+":"+min+":"+sec);
}
public static void main(String args[])
{
demo d1=new demo();
demo d2=new demo();
d1.input(12, 55, 55);
d2.input(12, 7, 6);
demo d3=d1.add(d2);
d3.display();
}
}
This example is a Sum for Date time and Time Zone(String Values)
String DateVal = "2015-03-26 12:00:00";
String TimeVal = "02:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
Date reslt = sdf.parse( DateVal );
Date timeZ = sdf2.parse( TimeVal );
//Increase Date Time
reslt.setHours( reslt.getHours() + timeZ.getHours());
reslt.setMinutes( reslt.getMinutes() + timeZ.getMinutes());
reslt.setSeconds( reslt.getSeconds() + timeZ.getSeconds());
System.printLn.out( sdf.format(reslt) );//Result(+2 Hours): 2015-03-26 14:00:00
Thanks :)
This will give you the time you want (eg: 21:31 PM)
//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime()));
tl;dr
LocalDateTime.parse(
"2018-01-23 01:23:45".replace( " " , "T" )
).plusHours( 2 )
java.time
The modern approach uses the java.time classes added to Java 8, Java 9, and later.
user enters in the format YYYY-MM-DD HH:MM:SS
Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T.
String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45
Parse as a LocalDateTime given that your input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
add two hours
The java.time classes can do the math for you.
LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;
Time Zone
Be aware that a LocalDateTime does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.
To define an actual moment, you must specify a zone or offset.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Define an actual moment, a point on the timeline by giving a context with time zone.
If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime rather than LocalDateTime.
About java.time
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.

Categories