Converting string to java.util.date - java

I am trying to convert string in java.util.date but I am having following errors:
HelloWorld.java:10: error: incompatible types: Date cannot be converted to String
return FORMATTER.parse(date);
^
HelloWorld.java:16: error: incompatible types: String cannot be converted to Date
Date date = convertStringToDate("2015-08-03 09:19:00.000");
My code is below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld{
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static String convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}
public static void main(String []args){
Date date = convertStringToDate("2015-08-03 09:19:00.000");
System.out.println(date);
}
}

Change your method signature into this instead:
public static Date convertStringToDate(String date)
SimpleDateFormat.parse returns a Date, not a String.
Also, you need to handle the checked ParseException that the parse method may throw, either by declaring throws ParseException in the signature (and handling the exception in main), or by wrapping the exception into a RuntimeException (effectively terminating the program when bad input is given):
public static Date convertStringToDate(String date) {
if (date != null) {
try {
return FORMATTER.parse(date);
} catch (ParseException e) {
// nothing we can do if the input is invalid
throw new RuntimeException(e);
}
}
return null;
}
Finally, you should notice that you can only parse hour values ranging from 1 to 12 with your current format (yyyy-MM-dd hh:mm:ss). If you'd want to parse according to the 24-hour clock, you should use the HH pattern for the hour part instead:
private static final DateFormat FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");

Your specified format is not matching with data format.
format "yyyy-MM-dd hh:mm:ss" is NOT compatible with data "2015-08-03 09:19:00.000" because of two reason: (1) AM/PM is missing in date as 'hh' takes 1-12 hrs , and (2) milliseconds present in date string
Replace below mentioned line and your issue will be resolved.
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But, none of the above mentioned issue can cause the exception you got as milliseconds is ignored by default.
Possible reasons of exception are return type of method "convertStringToDate" or hh having value beyond the range between01 and 12.
change return type from String to Date
Change date format hh to HH.

It is because you are trying to return a String from your method. Change it to Date.
public static Date convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}

Related

Java SimpleDateFormat Cannot format given Object as a Date

I am trying to convert string to date using date format and used the following code but its shows an error.
public static Date ConvertStringtodate(String Date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date Teststart = dateFormat.parse(Date);
return Teststart;
}
public static void main(String[]agrs) throws ParseException {
System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
}
Here is the error
Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date at
java.text.DateFormat.format(DateFormat.java:310) at
java.text.Format.format(Format.java:157)
At the main method, you are sending date as "2022.02.10 17:54:55". However, you wrote format of the pattern as "yyyy-MM-dd hh:mm:ss". Change the pattern at the SimpleDateFormat constructor as "yyyy.MM.dd HH:mm:ss".
The problem for me was the slashes '/' in the date input. for some reason the. The input string was "01/01/1991" instead of "01-01-1991". So I just replaced the slashes with dashes and everything worked just fine.
private Date convertStringToDate(String payload) throws ParseException {
payload = payload.replace("/", "-");
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
java.util.Date utilDate = formatter.parse(payload);
return new Date(utilDate.getTime());
}

Unexpected Output while trying yo convert String to date using FastDateFormat

Problem:
I need to pass Date class Object to a function and that Date Object should contain one Day ahead of the System Time.
For Ex:
If Today's Date is 2017-04-20 17:01:31.Then,Date Object should contain 2017-04-21 17:01:31
Is it possible to store a specified format into Date Class Object and pass into it.
I tried the following thing and it didn't work.
Can anyone guide me if it is possible through Code or should I use SQL Query Concept to add a Day.
Below is my Code
public static void main(String[] args) throws ParseException {
String dateFormat="yyyy-MM-dd HH:mm:ss";
String s2=addDate(dateFormat);
convertStringToDate(s2,dateFormat);
}
public static Date convertStringToDate(String dateInStr, String dateFormat) throws ParseException
{
FastDateFormat fdf=FastDateFormat.getInstance(dateFormat);//("yyyy-MM-dd HH:mm:ss");
Date date = null;
date = fdf.parse(dateInStr);
System.out.println("From convertStringToDate ");
System.out.println(date);
return date;
}
public static String addDate(String dateFormat) throws ParseException{
FastDateFormat fdf=FastDateFormat.getInstance(dateFormat);
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE,1);
String s1=fdf.format(c.getTime());
System.out.println("From addDate ");
System.out.println(s1);
return s1;
}
Expected Output from convertStringToDate:
2017-04-21 17:01:31
OutputShown from convertStringToDate:
Fri Apr 21 17:01:31 IST 2017
You need to obtain the instance of class Date. In your method addDate you get the required Date and then convert it to String and return a String. And then you convert your String back to Date Why don't you just return Date from your method addDate and be done with it?

Java SimpleDateFormat.parse throws : Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)

Hello i have the following string with datetime:
public static String nextOccurenceString = "2015-10-06T08:00:00+00:00";
And i want to parse and format string into the following format by following pattern:
public static String pattern = "yyyy-MM-dd HH:mm:ss";
But when i try to call method which should parse the date string into date object i always get exception:
Unparseable date: "2015-10-06T08:00:00+00:00" (at offset 10)
Method is following:
public static void convertStringToDate(String dateString) {
try {
SimpleDateFormat sdf;
sdf = new SimpleDateFormat(pattern, Locale.ENGLISH);
Date test = sdf.parse(nextOccurenceString);
Logger.d(test.toString());
} catch (Exception e) {
Logger.e(e.getMessage());
}
}
And I'm using the standard formatting and parsing class:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
How can i solve it please? Should replace something in nextOccurenceString or can i work with string in format like:
"2015-10-06T08:00:00+00:00" ?
Many thanks for any advice.
Your pattern is wrong. It must be:
public static String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
For more information read the javadoc of SimpleDateFormat
The correct pattern for your string is yyyy-MM-dd'T'HH:mm:ssZ (ISO 8601) and not yyyy-MM-dd HH:mm:ss

how to convert string into date? JAVA

I have this string: 7 -Jun- 2014.
I want to convert to java.utils.Date;
I use this Code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
but I get this exception :
java.text.ParseException: Unparseable date: "7-Jun-2013"
at java.text.DateFormat.parse(Unknown Source)
at ma.abcsolution.util.Test.main(Test.java:15)
try using
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
the SimpleDateFormat look at the given string like it you tell it to, so in your example it look for a string with 2 chars for days, followed by a '/' sign and then 2 chars for month and so on
Using SimpleDateFormatter you can convert from date string to date and date to date String
public final class DateUtil {
private static final String DEFAULT_DATE_FORMAT = "dd-MMM-yyyy";
private DateUtil() {
}
public static final String formatDate(final Date date, final String dateFormat) {
DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
return format.format(date);
}
public static final Date formatDate(final String date) throws ParseException {
return formatDate(date, DEFAULT_DATE_FORMAT);
}
public static final Date formatDate(final String date, final String dateFormat) throws ParseException {
DateFormat format = new SimpleDateFormat(dateFormat);
return format.parse(date);
}
}
Whenever you are going yo format date please verify the format you are using
In your case you used dd/MM/yyyy but date you used in format dd-MMM-yyyy.
Use
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
to format the date. You used the wrong format with the / signs.
See also:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date date = new SimpleDateFormat("d-MMM-yyyy").parse("7-Jun-2014");
Use this code. It is simple.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static void main(String args[]){
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
Date date=new Date(dateInString);
System.out.println(ft.format(date));
}
}

How to get UTC time without SimpleDateFormat? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 8 years ago.
I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.
Read up on Joda-Time. That is a better API for such things than the java date and calendar classes
maybe this can help you:
Calendar.getInstance(java.util.TimeZone)
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.
So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {
public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private Date date = new Date();
private final SimpleDateFormat format;
public DateTimeHelper(String dateTimeFormat) {
format = new SimpleDateFormat(dateTimeFormat, Locale.US);
}
public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
this(dateTimeFormat);
try {
format.setTimeZone(timeZoneUTC);
Date utc = format.parse(utcTimeString);
format.setTimeZone(TimeZone.getDefault());
String local = format.format(utc);
date = format.parse(local);
} catch (ParseException e) {
// nothing
}
}
public Date getDate() {
return date;
}
public Date toUtc() {
String temp = toString();
format.setTimeZone(timeZoneUTC);
try {
return format.parse(temp);
} catch (ParseException e) {
return date;
}
}
#Override
public String toString() {
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
public String toUtcString() {
format.setTimeZone(timeZoneUTC);
return format.format(date);
}
}
And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {
public MySqlDateTimeHelper() {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
}
public MySqlDateTimeHelper(String utcTimeString) {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
}
public static String getCurrentTimestampUtc() {
MySqlDateTimeHelper current = new MySqlDateTimeHelper();
return current.toUtcString();
}
}

Categories