SimpleDateFormat String - java

I have this code block where argument to dateFormat.format will always be a string thats why I did .toString() here. I am getting error "Cannot format given Object as a Date".
Is there any way to do this ? Note that string is coming from database I used new Date() as a sample here.
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormat.format(new Date().toString());

DateFormat#format accepts a Date, not a string.
Use
String sCertDate = dateFormat.format(new Date());
If you have a string coming from the database that is a specific format and you want to convert into a date, you should use the parse method.
#Sonesh - Let us assume you have a string in the database that happens to represent a Date ( might be better to store the object in the database as dates? ) , then you would first parse it to the format you wanted and then format it to the string format you wanted.
// Assumes your date is stored in db with format 08/01/2011
SimpleDateFormat dateFormatOfStringInDB = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = dateFormatOfStringInDB.parse(yourDBString);
SimpleDateFormat dateFormatYouWant = new SimpleDateFormat("MMMMM dd, yyyy");
String sCertDate = dateFormatYouWant.format(d1);

There are two applications of SimpleDateFormat:
parse a string - when you have a date represented as string, and you want to get the corresponding Date object. Then use dateFormat.parse(string)
format a date - when you have a Date object and you want to format it in a specific way (usually in order to show it to a user). In that case use dateFormat.format(date)
The two methods are reciprocal - one takes a date and returns a string, and the other takes a string and returns a date.
For your particular case, perhaps you need .parse(..). But note that every 'self-respecting' database driver should have an option to return a Date rather than some string representation. If you happen to be storing dates as string in the DB - don't do that. Use the native date type.

If you need to read a Date with one String format and output it to another String format, you need 2 formatters, for example:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMMMM dd, yyyy");
String output = outputFormat.format(inputFormat.parse(input));

Related

How to set the timestamp if there's a part in the String missing?

For example you have:
String datetime = new String("2008-05-09");
Timestamp.valueOf( datetime )
The value will be: 2008-05-09 00:00:00.0 without any exception.
Another example:
String datetime = new String("2008-05-09 13:34");
Timestamp.valueOf( datetime )
The value will be: 2008-05-09 13:34:00.0 without any exception.
Thanks,
If I understand you right, you are going to get a string that is only part of a timestamp and you want to parse it? You can use SimpleDateFormat if you know the format you will receive. https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
I assume you want to convert Strings into timestamp objects regardless of whether they contain time part or not.
You can do it by this way: String -> Date -> TimeStamp
To convert String into Date, you can use DateUtils library (with multiple date formats) and then, you can convert date into timestamp. Have a look at the below example:
String[] dateFormats = new String[]{"yyyy-MM-dd", "yyyy-MM-dd hh:mm", "yyyy-MM-dd hh:mm:ss"};
for(String dateString : new String[]{"2008-05-09", "2008-05-09 13:34", "2008-05-09 13:34:40"}){
Date date = DateUtils.parseDate(dateString, dateFormats);
Timestamp timeStamp = new Timestamp(date.getTime());
System.out.println(timeStamp);
}

Convert string to yyyyMMdd format

I have a String reading clients date of birth and I am trying to assign to another String but I need to assign in yyyymmdd format. I am not sure what format client set his birth date.
Here is my code.
String birthDate = request.getClient().getBirthDate();
patient().setDob_yyyymmdd(birthdate);
Do you have to create a SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//Put the incoming format
Then create a
Date date =sdf.parse(yourincomingdate);
Then create a DateFormat to transfor your Date to another format
DateFormat df = new SimpleDateFormat("HH:mm");
String reportDate = df.format(date);
There is no way you can guess in which format is the input date.
However, if you can manage to discover which is the input format, you can use the SimpleDateFormat class to convert Date objects to Strings and vice-versa.
String inputDate, inputFormat; //inputFormat may be, eg, "MM-dd-yyyy", that is the part you still need to find out
Date foo = new SimpleDateFormat(inputFormat).parse(inputDate);
String output = new SimpleDateFormat("ddMMyyyy").format(foo);

Getting formatted date in date format rather than String

I'm running the program written below, but instead of printing in mm/dd/yyyy hh:mm format it prints in the normal date format(ie. Day Date and time)
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy hh:mm");
Date date = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
The reason i'm doing this is because the existing method accepts parameters in Date format, so i need to send the above mentioned date object to it.
Please point out the mistake or suggest some other alternative.
Thanks
Date objects don't have a format. The Date class is a wrapper around a single long, the number of milliseconds since the epoch. You can't "format" a Date, only a String. Pass around a Date/Calendar internally, and format it whenever you need to display it, log it, or otherwise return it to the user.
Change the format to MM/dd/yyyy. Month is denoted by capital M.
Check below URL for valid formats
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your formatter works quite fine (apart from the mm vs. MM bug). You get a formatted string from the date and then create a copy from your date by parsing the formatted string:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date now = Calendar.getInstance().getTime();
String formattedNow = sdf.format(now); // == "09/24/2013 01:59"
Date now2 = sdf.parse(formattedNow); // == now

How to display the date format in android?

String date="21-04-2013";
In my android application
Here i want to display the date in the following format like "21" is a separate string and month is like "Apr" as a separate string and year is like "13"as a separate string without using String functions.Can anybody plz give some suggestions to convert in this format?any date function is available?
You'll want to take a look at the SimpleDateFormat class for parsing the date string. In order to end up separate strings without using string functions, you'll probably need multiple formatters for the output too. It would look somewhat like this:
String date = "21-04-2013";
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); // input date
Date outDate = dateFormatter.parse(date);
SimpleDateFormat dayFormatter = new SimpleDateFormat("dd"); // output day
SimpleDateFormat monthFormatter = new SimpleDateFormat("MMM"); // output month
SimpleDateFormat yearFormatter = new SimpleDateFormat("yy"); // output year
String day = dayFormatter.format(outDate);
String monthy = monthFormatter.format(outDate);
String year = yearFormatter.format(outDate);
If you were to use String.split(), you could get rid of at least two of the formatters in above snippet.
This is the class you'll need: DateFormat
Examples are provided in the link, but in short, you'll first need to parse the date, and then format the date again.

change string to date as per the required date Format

I have to get a Date in type Date, not in String.
I have this code:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e 05/24/11
Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e 05/24/11
// And in type Date, not in type String
If anyone could help, thanks
The Date object just represents a point in time and has no notion of a format (or time zone). If you print out a Date object it first converts it to a String using the default formatting of EEE MMM dd HH:mm:ss zzz yyyy. If you want a specific formatting when you print it or otherwise represent it as a String, you'll need to use a formatter just like you already have.
In other words, you want Date.toString() to return the same as DateFormat.format()? You could just do exactly that:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
But do you really want to mix up presentation (date format) with your data?
There is no problem here, you have a Date representing and can save it into the DB as it is now. If you print it to the console it gets formatted according the default rules, this is why you think it is different from what you need, but it has actually already the right value.
So just go ahead and put it into your DB.
Chances are that you DB will hold on getting a Timestamp, in this case you can create one:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
and save this one.

Categories

Resources