Java convert date to readable form? - java

I have Date objects stored in database. Now am when the form I am displaying presents all the data in my objects, it also displays date. I don't want it to show the long detailed form. All I need is DD/MM/YYYY format. This is what am getting now:
Sun Jan 01 00:00:00 GMT+03:00 2012
Now I followed an online tutorial and got this code going:
public String changeDateFormat(Date date){
String pattern = "MM/dd/yyyy";
//Date datex = null;
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
date = format.parse(date.toString());
System.out.println(date);
} catch (ParseException e) {
System.err.print(e);
}
return date.toString();
}
and I invoke it when am getting the value of global variable:
public String getEndDate() {
return changeDateFormat(endDate);
}
the output shown above is the result. What can I do to only and only get DD/MM/YYYY without time if possible?
Thanks

Just
return (new SimpleDateFormat("dd/MM/yyyy").format(dateInstance));

Related

Any possibility to parse a string to date object without converting to your system timezone with simpleDateFormat?

I have a birthday (Date object) that I would like to convert to UTC time.
I am able to use formatting to convert my locale time to UTC time by SimpleDatePattern. However when I format it, it converts the Date object to String. I tried parsing it (which returns a Date object) but converts it to local time system again. Here is my code below. Any help on converting the birthday field to UTC time while remaining a Date object and not a string?
public Date getBirthDay() {
if (birthDay == null) {
return null;
}
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedBirthDate = utcFormat.format(birthDay);
try {
System.out.println("I am here within try block" + utcFormat.parse(formattedBirthDate));
birthDay = utcFormat.parse(formattedBirthDate);
} catch (ParseException e) {
e.printStackTrace();
}
return (Date) birthDay.clone();
}

get SimpleDateFormat return wrong answer

I need to convert timestamp string to long.
Here is my input string:
2016-08-10T11:24:57.182+0300
here is code witch I am trying to use for converting:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.sssZ");
try {
Date date = simpleDateFormat.parse(timestamp);
long time = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
result: 1470817622000
but when i check this long time here, it returns me this string:
10 august 2016 8:27:02 GMT
but this is different from the input string.
any idea why it happens and how to fix this?

Android method for consistent DateTime formatting across application

My application queries a SQLite DateTime string and I'm trying to write a single method than I can use across my application so that DateTime timestamps are formatted consistently. So far I have,
public class DateTimeUtils {
public static String formatDueDate(String queryResponse) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss z", Locale.US);
Date result = new Date();
try {
result = sdf.parse(queryResponse);
} catch (ParseException e) {
e.printStackTrace();
}
return result.toString();
}
}
Which is used in a situations such as
taskViewHolder.mDue.setText(formatDueDate(task.getDue().toString()));
I'd like the output to look like June 27, 20015, 5:30PM
The raw datetime String takes the form: 2015-08-10T17:28:00.000-04:00
My problems are currently the resulting timestamp format is incorrect and instead looks like Sun Aug 02 17:29:03 EDT 2015 and instead of parsing the inputted timestamp, just returns the current datetime.
I believe this is because my formatting is actually throwing an exception and i'm just returning the current Date() object. What should I change so that the datetime string is parsed correctly?
Well, since you're creating the Date object outside the try block, you're right, if there is a parsing error, the current date will return. SimpleDateFormat does that work for you in the parse method. You could reduce the possibility of the current date returning by assigning the Date variable to null instead of instantiating a new object.
If you already get an correct Date class, maybe you can generator your special format by Calendar class and StringBuilder class.
Like below:
String[] monthString = new String[12];
if (monthString[0] == null) {
// Get month string by android locale
// The String will like Jule or May ...
Map<String, Integer> months = Calendar.getInstance().getDisplayNames(Calendar.MONTH, Calendar.LONG, getResources().getConfiguration().locale);
for (int i = 0; i < 12; i++) {
for (String month : months.keySet()) {
if (i == months.get(month).intValue()) {
monthString[i] = month;
months.remove(month);
break;
}
}
}
}
Calendar calendar=Calendar.getInstance();
calendar.setTime(result);
StringBuilder sb=new StringBuilder();
sb.append(monthString[calendar.get(Calendar.MONTH)]);
//spec your format string...
Hope this can help you.

Java Unparseable Date difference in formats

How to differentiate between data-entry being (a) invalid date or (b) invalid format?
I have the following code for handling date inputs from an text file.
public boolean dateIsValid(String date) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setLenient(false);
try {
Date dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
I have everything working as I want it to. The only problem I have is I am unable to differentiate the different parse exceptions thrown. For example:
if String date = 18/10/2012 --> java.text.ParseException: Unparseable date: "18/10/2012"
if String date = 2-12-2001 --> java.text.ParseException: Unparseable date: "2-12-2001"
As you can see, both the wrong formats throw the same error. How can I differentiate them so that I can handle them differently?
EDIT
To be more precise, in case of date 18/10/2012, I should throw an invalid date error and in the case of date 2-12-2001, I need to throw an invalid format exception. I dont need to handle different formats. I just need a way of getting different exceptions for these two different cases.
The issue seems to be at this line
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
For the first error it looks like that the date is coming first and the month later so it should be like
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Second error shows the incorrect format of the date supplied since it is containing - whereas you are expecting the format containing / ie like
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
If you want to handle different formats then try like this:
String[] formatDates= {"MM/DD/yyyy", "dd/MM/yyyy", "MM-dd-yyyy","dd-MM-yyyy"};
Date tryParse(String dateString)
{
for (String formatDate: formatDates)
{
try
{
return new SimpleDateFormat(formatDate).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Unless you write code to parse the date strings yourself, you will not know why the format threw the exception.
I recommend a variation of the R. T. answer above.
Specifically, instead of creating a new formatter every time, create four (in that example) formatters at startup (in the constructor or in a static block).
I would use
public Date dateIfValid(String format, String date) {
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
return dateParsed = (Date) formatter.parse(date);
} catch (ParseException e) {
return null;
}
}
Date mmddyy = dateIfavlid("MM/dd/yy", date.replace("[^0-9]", "/"));
Date ddmmyy = dateIfavlid("dd/MM/yy", date.replace("[^0-9]", "/"));
if (mmddyy != null && ddmmyy == null) {
Note: this can be used to detect ambigous dates such as 01/02/03 which might be 3rd Feb 2001

how to change date format in java?

i am getting my date input as a string in the format dd-mm-yy through jsp page. Because this format is better to understand . But now i want to store the date in yyyy-MM-dd HH:mm:ss format in my database. I am using the following code.
try
{
String s="30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
System.out.println(d1);
System.out.println(ft.format(d1));
} catch(Exception e) {
System.out.println("Exception:"+e);
}
My Jsp date format is dd-mm-yy, but it gives answer as
Tue Oct 04 00:00:00 IST 35
0035-10-04 00:00:00
what is my mistake?
can tell me anyone please
Thank you.
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
should be
d1=new SimpleDateFormat("dd-MM-yyyy").parse(s);
because the input date String you've provided String s="30-04-2013"; is of the format, dd-MM-yyyy. Hence, to parse this, you need to give dd-MM-yyyy format in your SDF.
Change the format in your code from yyyy-MM-dd to dd-MM-yyyy. A simple debug would have solved this issue.
i think you need to pass the Date object to format() method of SimpleDateFormat class instead of passing string to it
just try to do like as follows
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted_date = ft.format(new Date());
System.out.println(formatted_date);
let me know the status
happy coding
See below the working program. See the parse and format method.
import java.text.SimpleDateFormat;
public class DateParsing {
public static void main(String args[]) {
String s = "30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat nt = new SimpleDateFormat("yyyy-MM-dd");
try {
System.out.println(nt.format(ft.parse(s)));
}
catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}

Categories