I have my Date of Birth variable which is initially of type int. It is then parsed toString() and parsed to Date with simpleDateFormat.
The only issue is that it keeps returning it's default time including the date.
public Date getDob(){
String format = Integer.toString(this.dob);
try{
date = new SimpleDateFormat("ddMMyyyy").parse(format);
}catch(ParseException e){
return null;
}
return date;
}
Returns: Sat Jan 16 00:00:00 CET 1999 [ I want to remove the bold time ]
Thank you very much for your help!
Solution:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
return date;
}
You cannot change toString() method of Date class,
what you are doing is you are parsing some String to Date and returning Date instance and trying to print it which internally invokes toString() of Date and it has fixed format,
You can use format() method to convert Date to String and print it in whatever format you want
A java.util.Date object by definition has both a date portion and a time-of-day portion.
Date-Time != String
Understand that a date-time object is not a String. We create String representations of the date-time value contained within a date-time object, but doing so is generating a fresh String object completely separate from the date-time object.
LocalDate
If you want only a date, without the notion of time-of-day, use the LocalDate class found in both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time).
Joda-Time
By default, Joda-Time uses the ISO 8601 standard formats. If you want Strings in other formats, explore the DateTimeFormat class (a factory of DateTimeFormatters).
Example code in Joda-Time 2.3.
String input = "01021903"; // First of February, 1903.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyy" );
LocalDate dateOfBirth = formatter.parseLocalDate( input );
String outputStandard = dateOfBirth.toString(); // By default, the ISO 8601 format is used.
String outputCustom = formatter.print( dateOfBirth );
Try this one
Date originalDate = new Date();
long timeInMills = originalDate.getTime();
Date newDate = new Date(timeInMills);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
System.out.println(date);
output:
Wed Apr 30
If you want to store the date in long (in milliseconds) if needed.
For more pattern have a look at SimpleDateFormat
Related
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"));
I have a string coming to me in the following format "yyyy-MM-dd'T'HH:mm:ssZ" ex: 2020-09-09T09:58:00+0000" offset is UTC.
I need the string to be converted to a Date object without the offset "+0000" being applied, but I keep getting a different time when running my code:
DateTimeFormatter isoFormat = ISODateTimeFormat.dateTimeParser();
Date date = isoFormat.parseDateTime("2020-09-09T09:58:00+0000").toDate();
// Wed Sep 09 05:58:00 EDT 2020
As you can see above the date has changed.
Instead, I would like to keep the same date and time like: Wed Sep 09 09:58:00, so I can convert this Date object to a String with "yyyy-MM-dd", "HH:mm:ss", and "yyyy-MM-dd'T'HH:mm:ss" format respectively.
The first and most important part of the answer is: don’t convert to an old-fashioned Date. Either stick to Joda-Time or migrate to java.time, the modern Java date and time API, as already covered in the good answer by Arvind Kumar Avinash.
Since you are already using Joda-Time, I am showing you a Joda-Time solution. The trick for persuading the formatter into keeping the time and offset from the string parsed is withOffsetParsed().
DateTimeFormatter isoFormat
= ISODateTimeFormat.dateTimeParser().withOffsetParsed();
String incomingString = "2020-09-09T09:58:00+0000";
DateTime dateTime = isoFormat.parseDateTime(incomingString);
However! If I have guessed correctly that you want to store date and time in UTC (a recommended practice), better than withOffsetParsed() is to specify UTC on the parser:
DateTimeFormatter isoFormat
= ISODateTimeFormat.dateTimeParser().withZoneUTC();
Now you will also get the correct time if one day a string with a non-zero UTC offset comes in.
In any case we may now format your obtained DateTime into the strings you requested.
String dateString = dateTime.toString(ISODateTimeFormat.date());
System.out.println(dateString);
String timeString = dateTime.toString(ISODateTimeFormat.hourMinuteSecond());
System.out.println(timeString);
String dateTimeString = dateTime.toString(ISODateTimeFormat.dateHourMinuteSecond());
System.out.println(dateTimeString);
Output:
2020-09-09
09:58:00
2020-09-09T09:58:00
What was wrong with using Date? First, the Date class is poorly designed and long outdated. Second, a Date was just a point in time, it didn’t have a concept of date and time of day (they tried building that into it in Java 1.0, but gave up and deprecated it in Java 1.1 in 1997). So a Date cannot hold the date and time of day in UTC for you.
What happened in your code was that you got a Date representing the correct point in time. Only when you printed that Date you were implicitly invoking its toString method. Date.toString() confusingly grabs the JVM’s time zone setting (in your case apparently North American Eastern Time) and uses it for rendering the string to be returned. So in your case the point in time was rendered as Wed Sep 09 05:58:00 EDT 2020.
I recommend you do it with the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// The given date-time string
String strDateTime = "2020-09-09T09:58:00+0000";
// Define the formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ");
// Parse the given date-time string into OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, formatter);
// Output OffsetDateTime in the default format
System.out.println(odt);
// Print OffsetDateTime using the defined formatter
String formatted = formatter.format(odt);
System.out.println(formatted);
}
}
Output:
2020-09-09T09:58Z
2020-09-09T09:58:00+0000
Note: java.util.Date does not represent a Date/Time object. It simply represents the no. of milliseconds from the epoch of 1970-01-01T00:00:00Z. It does not have any time-zone or zone-offset information. When you print it, Java prints the string obtained by applying the time-zone of your JVM. I suggest you stop using java.util.Date and switch to the modern date-time API.
Using joda date-time API, you can do it as follows:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
public class Main {
public static void main(String[] args) {
// The given date-time string
String strDateTime = "2020-09-09T09:58:00+0000";
// Define the formatter
DateTimeFormatter isoFormat = ISODateTimeFormat.dateTimeParser();
DateTime dateTime = isoFormat.parseDateTime("2020-09-09T09:58:00+0000");
// Display DateTime in the default format
System.out.println(dateTime);
// Define formatter for ouput
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZoneUTC();
// Display DateTime in the defined output format
String formatted = outputFormat.print(dateTime);
System.out.println(formatted);
}
}
Output:
2020-09-09T10:58:00.000+01:00
2020-09-09T09:58:00+0000
I'm trying to format date in java using SimpleDateFormat class. I have written a function which takes in string as a parameter and returns date as a output having the desired format. The problem arises when i try to parse the date in order to convert the string to date , the value is returned as Wed Jul 03 00:00:00 IST 2019 , instead of yyyy-MM-dd format .
private static final String DOB_FORMAT = "yyyy-MM-dd";
public static Date convertStringToDateFormatYYYYMMDD(String date) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(DOB_FORMAT, Locale.ENGLISH);
Date parsedDate = null;
try {
parsedDate = sdf.parse(date);
LOG.info("Date formated " + parsedDate);
return parsedDate;
} catch (ParseException e) {
LOG.info("Date Parsing Issue - date :" + date);
}
}
return null;
}
The result value should be returned as yyyy-MM-dd, instead of Wed Jul 03 00:00:00 IST 2019
Avoid legacy date-time classes
I'm trying to format date in java using SimpleDateFormat class.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes, with the adoption of JSR 310.
ISO 8601
DOB_FORMAT = "yyyy-MM-dd"
That format happens to comply with the ISO 8601 standard.
The java.time classes comply with the standard as well, using those formats by default when parsing/generating strings.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
String input = "2019-01-23" ; // January 23, 2019
LocalDate localDate = LocalDate.parse( input ) ;
Text has formats, not date-time objects
You Question also says:
value is returned as Wed Jul 03 00:00:00 IST 2019 , instead of yyyy-MM-dd format .
Be clear that date-time objects do not have a “format”. Only text strings have a format. A date-time object is not a text string. A date-time object parses a text string to generate a date-time value, and a date-time object can generate text representing its date-time value. But the date-time object and the text are distinct and separate from one another.
Avoid java.util.Date
Date parsedDate = null;
The terrible java.util.Date class represents a date with time-of-day in UTC (an offset from UTC of zero hours-minutes-seconds). But you want only a date, without the time-of-day and without an offset or time zone. So square peg, round hole. Instead, use appropriate types. And stop using those legacy date-time classes; use only java.time classes.
Generating text
To generate a string in standard ISO 8601 format, simply call toString.
String output = localDate.toString() ;
2019-01-23
To generate a string automatically-localized:
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = localDate.format( f ) ;
See this code run live at IdeOne.com.
23 janv. 2019
Date object is not formatted itself. You can return a formatted String containing the information.
Mates,
I have a Date object which get populated with a value after reading from a excel
Date mydate = cell.getDateCellValue();
value loaded is *"Sat Jan 09 00:00:00 IST 2016"
I dont know why this format value is given out from excel though its displayed on different format in excel.
I want to convert this DATE into dd-mm-yyyy format. How can this be done?
Tried this
String ms= "Sat Jan 09 00:00:00 IST 2016" ;
SimpleDateFormat formater = new SimpleDateFormat("mm-dd-yy");
Date result = formater.parse(ms);
System.out.println(result);
but gives output same as input.
You need to create your own Date class and override toString method with which ever format you want it to return #ApachePOI
public class CustomDate extends Date
{
public CustomDate(String string)
{
super(string);
}
#Override
public String toString()
{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String format = formatter.format(this);
return format;
}
}
And the main method
public static void main(String[] args)
{
Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
String dateString = date.toString();
CustomDate customDate = new CustomDate(dateString);
System.out.println(dateString);
System.out.println(customDate.toString());
}
Use whatever format you want inside your toString method
Do not conflate a date-time object with text that represents its value. A java.util.Date has no “format”. You are seeing text generated by that object’s toString method. That text does not exist inside the object. That class’ toString lies, applying the JVM’s current default time zone to the UTC value actually stored inside. One of many reasons to avoid this class altogether.
That Date class is part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Convert your java.util.Date object to an Instant.
In Java 8 and later, look for new conversion methods added to the old classes. For Java 6 & Java 7, you'll be using the ThreeTen-Backport project. There you'll find a DateTimeUtil class offering conversion methods.
From our Instant, we can get a date. But first we must apply a time zone to move that Instant from UTC to the zone by which you want to perceive the date. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate a string using a DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd -MM-uuuu" , Locale.US ) ;
String output = zdt.format( f ) ;
I am facing an issue when I convert my string to date format.
This is what I have tried -
First try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
date = df.parse(completionDate1);
System.out.println(date); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
Second try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("yyyy/MM/dd").parse(completionDate1);
System.out.println(completionDate); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
The output I'm expecting is that, the completionDate should be Date format not String. I'm just printing the completionDate just to make sure the date format is getting getting converted.
The main intention of getting it in date format is I need this for an Update query so it has to be Date and not String.
Kindly let me know where I'm going wrong. I need this date format as I need to store this date in a database.
Thanks
You have to format the date after parsing it but your parsing format is also incorrect so its giving wrong output. Try
String completionDate1 = "21/10/2016";
System.out.println(completionDate1);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
date = df.parse(completionDate1);
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df1.format(date));
DEMO
Wrong pattern
First problem is that your defined parsing pattern does not match your input string. For 21/10/2016 pattern should be dd/MM/yyyy.
java.sql.Date versus java.util.Date
Second problem is that for database access you should be using the java.sql.Date class for a date-only value without time-of-day and without time zone. Not to be confused with java.util.Date which is a date and time-of-day value. You should specify the fully-qualified class name in such discussions as this Question.
Neither of these classes have a “format”. They have their own internal representation, a count from epoch.
java.time
Third problem is that you are using old outdated classes. In Java 8 and later, use java.time framework now built-in. In Java 6 & 7, use its back-port, the ThreeTen-Backport project. For Android, use the adaptation of that back-port, ThreeTenABP.
In the java.time classes we now have the LocalDate class for date-only values.
String input = "21/10/2016"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Hopefully some day JDBC drivers will be updated to directly use the java.time types. Until then, use the new methods added to the old java.sql types to convert.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
Now pass that java.sql.Date object to the setDate method on a PreparedStatement object for transmission to a database.
Note that at no time did we make use of any more strings. We went from original input String to java.time.Date to java.sql.Date.
At no point did we use java.util.Date. Check your import statements to eliminate java.util.Date.
By the way, to go the other direction from java.sql.Date to LocalDate:
LocalDate localDate = mySqlDate.toLocalDate();
Use below code
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("dd/MM/yyyy").parse(completionDate1);
String date = new SimpleDateFormat("yyyy/MM/dd").format(completionDate);
System.out.println(date);
You can try this
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String completionDate = df.format(request.getParameter("completion_date"));
System.out.println(completionDate);