Date changing from one format to another format - java

I am trying to parse the date from one format to another format, but getting the parse exception. Please help me out on this issue.
String Orgdate= "2016-11-14T11:12:13";
java.util.Date tardate = null;
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/mm/yyyy HH24:MI:SS");//Exception is in this line.
try {
targetdateformat = dateFormat2.parse(Orgdate);
} catch (ParseException e) {
e.printStackTrace();
}
Above code giving me date but different format,i am looking for date like below mention.
('14/11/2016 11:12:13')
Time format is 24 Hrs.

why not just do a simple hardcode to get the format you would like. For example...
String date = "2016-11-14T11:12:13";
String newDate = date.charAt(8) + "" + date.charAt(9) + "/" +
date.charAt(5) + "" + date.charAt(6) + "/" +
date.substring(0, 4) + " " + date.substring(11, 19);
System.out.println(newDate);

You need to parse to Date then format the date string to convert it into another format
String Orgdate= "2016-11-14T11:12:13";
java.util.Date tardate = null;
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
tardate = dateFormat2.parse(Orgdate);
System.out.println(tardate); // Mon Nov 14 11:12:13 UTC 2016
} catch (ParseException e) {
e.printStackTrace();
}
String formatted = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(tardate);
System.out.println(formatted); 14/11/2016 11:12:13
If you are using Java8 you can try below
LocalDateTime dateTime = LocalDateTime.parse("2016-11-14T11:12:13", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
String formattedDate = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")); // 14/11/2016 11:12:13

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date a = sdf.parse("2016-08-12T08:29:47");
sdf.applyPattern("dd/MM/yyyy HH:mm:ss");
System.out.println(sdf.toPattern()); // to see if new pattern applied
System.out.println(sdf.format(a)); // get output in desired format

Related

How to print date in GMT format? [duplicate]

I have a string "2014-07-02T17:12:36.488-01:00" which shows the Mountain time zone. I parsed this into java.util.date format. Now I need to convert this to GMT format. Can anyone help me??
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Object dd = null;
try {
dd=sdf.parseObject("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();`enter code here`
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:+ gmtDateFormat.format(dd));
There are a few problems in your code. For example, the format string doesn't match the actual format of the string you are parsing.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Object dd = null;
try {
dd = sdf.parse("2014-07-02T17:12:36.488-01:00");
System.out.println(dd);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:" + gmtDateFormat.format(dd));
To print the current date in whatever timezone you like, set the timezone you want to use on the SimpleDateFormat object. For example:
// Create a Date object set to the current date and time
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current date and time in IST: " + df.format(now));

Date parsing yyyy-MM-dd'T'HH:mm:ss in Android

My string date --> 2016-10-02T00:00:00.000Z. I want to get only date from this string. I tried to parse through below coding but it throws me error! I have exactly the same format as mentioned in the string. Any answers?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
try {
Date myDate = sdf.parse( dateofJoining.replaceAll( "([0-9\\-T]+:[0-9]{2}:[0-9.+]+):([0-9]{2})", "$1$2" ) );
System.out.println("Date only"+ myDate );
} catch (ParseException e) {
e.printStackTrace();
}
I also tired below code,
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The error which i get
java.text.ParseException: Unparseable date: "2016-10-02T00:00:00.000Z" (at offset 19)
05-12 00:18:36.613 4330-4330/com.vroom.riderb2b W/System.err: at java.text.DateFormat.parse
change the simple date format to use: yyyy-MM-dd'T'HH:mm:ss.SSSZ
in your code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
Date date = format.parse(dtStart.replaceAll("Z$", "+0000"));
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you want to get date/mm/yy from it:
use:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.i("DATE", sdf.format(date)); //previous date object parsed
if you want output format: hour:minute AM/PM
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(date));
EDIT
More easier option is to split the string in two parts like:
String dateString = "2016-10-02T00:00:00.000Z";
String[] separated = dateString.split("T");
separated[0]; // this will contain "2016-10-02"
separated[1]; // this will contain "00:00:00.000Z"
try with this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Try
Calendar calendar = Calendar.getInstance();
TimeZone localTZ = calendar.getTimeZone();
String format1 = "yyyy-MM-dd"; //will return 2017-01-31
String format2 = "dd"; //will return DAY only like 31
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTZ );
String result = sdf.format(your_date);
For me it's worked like this:
textView_last_comm.setText(parseDateFormat(passDetailsModel.getLast_comm(), "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "dd/MM/yy HH:mm"));
public static String parseDateFormat(String dateToFormat, String inputFormat, String outputFormat) {
SimpleDateFormat inputFormat = new SimpleDateFormat(inputFormat);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputFormat);
Date date = null;
String str = null;
try {
date = inputFormat.parse(dateToFormat);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
You can get date easily by using String.substring() method:
String string = "2016-10-02T00:00:00.000Z";
String date = string.substring(0, 10);
Log.d("SUCCESS", "DATE: " + date);
OUTPUT:
D/SUCCESS: DATE: 2016-10-02

GSON ignores setDateFormat when using Date Adapter for UTC timezone [duplicate]

I'm having trouble changing the date format to dd/MMM/yyyy.
Here is my current implementation:
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MMM-dd";
//Start Date
String str4=label.getText();
java.util.Date toDate = null;
//System.out.println(str4);
//End Date
String str5=lblNewLabel_3.getText();
java.util.Date newDateString = null;
SimpleDateFormat format = new SimpleDateFormat(OLD_FORMAT);
try {
toDate=format.parse(str4);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newDateString=format.parse(str5);
format.applyLocalizedPattern(NEW_FORMAT);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
output: [Tue May 28 00:00:00 WST 2013]
can someone help me with this, thanks! :D
I add this while statement then the date format sets to default again..
System.out.println("From " + toDate);
System.out.println("To " + newDateString );
Calendar cal2 = Calendar.getInstance();
cal2.setTime(toDate);
System.out.println(toDate);
while (cal2.getTime().before(newDateString)) {
cal2.add(Calendar.DATE, 1);
Object datelist=(cal2.getTime());
List<Object> wordList = Arrays.asList(datelist);
System.out.println(wordList);
}
java.util.Date does not have a format. It is simply the number of millisecond since January 1, 1970, 00:00:00 GMT
When you do a System.out.println(new Date()) it is simply providing the Date objects default toString methods output.
You need to use a DateFormat to actually format the Date to a String
public class TestDate01 {
public static final String OLD_FORMAT = "yyyy-MM-dd";
public static final String NEW_FORMAT = "yyyy-MMM-dd";
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
String oldValue = "2013-05-29";
Date date = new SimpleDateFormat(OLD_FORMAT).parse(oldValue);
String newValue = new SimpleDateFormat(NEW_FORMAT).format(date);
System.out.println("oldValue = " + oldValue + "; date = " + date + "; newValue = " + newValue);
} catch (ParseException exp) {
exp.printStackTrace();
}
}
}
Which outputs...
oldValue = 2013-05-29; date = Wed May 29 00:00:00 EST 2013; newValue = 2013-May-29
Extended to meet changed requirements
You're making the same mistake. Date is a container for the number of milliseconds since the epoch, it does not have any format of it's own and instead uses its own format.
try {
Date toDate = new Date();
String newDateString = "2013-05-31";
System.out.println("From " + toDate);
System.out.println("To " + newDateString);
Date endDate = new SimpleDateFormat(OLD_FORMAT).parse(newDateString);
System.out.println("endDate " + endDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(toDate);
System.out.println(toDate);
SimpleDateFormat newFormat = new SimpleDateFormat(NEW_FORMAT);
while (cal2.getTime().before(endDate)) {
cal2.add(Calendar.DATE, 1);
Date date = (cal2.getTime());
System.out.println(date + "/" + newFormat.format(date));
}
} catch (Exception exp) {
exp.printStackTrace();
}
Which outputs...
From Wed May 29 15:56:48 EST 2013
To 2013-05-31
endDate Fri May 31 00:00:00 EST 2013
Wed May 29 15:56:48 EST 2013
Thu May 30 15:56:48 EST 2013/2013-May-30
Fri May 31 15:56:48 EST 2013/2013-May-31
You while does not make sense.
Object datelist=(cal2.getTime());
List<Object> wordList = Arrays.asList(datelist);
cal2.getTime() returns a Date, then you try and create a list from it...maybe I'm missing something though...
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String str4=label.getText();
Date date=null;
try {
date = formatter.parse(str4);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
formatter = new SimpleDateFormat("dd/MMM/yyyy");
System.out.println("Date :" +formatter.format(date));
Check the below code snippet
try {
SimpleDateFormat sdin = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdout = new SimpleDateFormat("yyyy-MMM-dd");
Date date = sdin.parse("2013-05-31");
System.out.println(sdout.format(date));
} catch (ParseException ex) {
Logger.getLogger(TestDate.class.getName()).log(Level.SEVERE, null, ex);
}
If you want to display the date in a certain format, you should be using format function and use String output to display, and not a date object
e.g. Consider this code:
String pattern = "dd/MM/yyyy";
DateFormat df = new SimpleDateFormat(pattern);
Date d = new Date();
try {
String outputString = df.format(d);
System.out.println("outputString :"+outputString);
} catch (ParseException e) {
e.printStackTrace();
}
parse function is just to parse a string from a particular format to create a Date object but it will not change any of date object display properties.
System.out.println(format.format(toDate))
This will display the date in required format.
I wrote a static utility method that you can just drop in and use...and hopefully it is clear enough to demonstrate the proper use of the SimpleDateFormat parse() and format() methods:
/**
* Returns a reformatted version of the input date string, where the format
* of the input date string is specified by dateStringFormat and the format
* of the output date string is specified by outputFormat. Format strings
* use SimpleDateFormat format string conventions.
*
* #param dateString input date string
* #param dateStringFormat format of the input date string (e.g., dd/MM/yyyy)
* #param outputFormat format of the output date string (e.g., MMM dd, yyyy)
*
* #return reformatted date string
*
* #throws ParseException if an error occurs while parsing the input date
* string using the provided format
*
* #author Steve
*/
public static final String reformatDateString(final String dateString,
final String dateStringFormat,
final String outputFormat)
throws ParseException {
final SimpleDateFormat dateStringParser = new SimpleDateFormat(dateStringFormat);
final SimpleDateFormat outputFormatter = new SimpleDateFormat(outputFormat);
return outputFormatter.format(dateStringParser.parse(dateString));
}
You call it as follows:
System.out.println(reformatDateString("2013-5-28", "yyyy-MM-dd", "dd/MMM/yyyy"));
Which, in this example, will output this:
28/May/2013
The basic idea is that you generally use a SimpleDateFormat instance for one of two things:
To convert a String containing a date with a known format to a java.util.Date instance...using the parse() method, or
To convert a java.util.Date instance to a String of a specified format...using the format() method.
I am doing both in one line in the method that I wrote using the two different SimpleDateFormat instances that I create in that method - one created using the input format (for parsing the original String into a Date instance)...and one created using the output format (for converting the created Date back into a String with the desired format).

Java convert date to sql timestamp

I'm trying to convert a date (string) extracted from a csv file, convert it to sql timestamp and upload using prepared statement. What I have is:
String test = "8/10/2014 16:59";
DateFormat fromFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
toFormat.setLenient(false);
Date date2 = null;
try {
date2 = toFormat.parse(test);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf(date2);
//java.sql.Timestamp sqlDate2 = new java.sql.Timestamp(timestamp);
//sql_statement.setTimestamp(1, ts2);
As you can see my code is messy as I'm trying to solve this problem. I'm always getting an error in eclipse:
java.text.ParseException: Unparseable date: "8/10/2014 16:59"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.syntronic.client.thread.ORCThreadTejasInv.uploadOracleDBOptical(ORCThreadTejasInv.java:555)
at com.syntronic.client.thread.ORCThreadTejasInv.connectOracleDB(ORCThreadTejasInv.java:170)
at com.syntronic.client.thread.ORCThreadTejasInv.retrieveOracleTejas(ORCThreadTejasInv.java:125)
at com.syntronic.client.thread.ORCThreadTejasInv.run(ORCThreadTejasInv.java:84)
at java.lang.Thread.run(Thread.java:745)
I even try using:
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
String yourformattedDate = sdf.format(test);
and diff error shows up"
Exception in thread "Thread-6" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:301)
at java.text.Format.format(Format.java:157)
at com.syntronic.client.thread.ORCThreadTejasInv.uploadOracleDBOptical(ORCThreadTejasInv.java:562)
at com.syntronic.client.thread.ORCThreadTejasInv.connectOracleDB(ORCThreadTejasInv.java:170)
at com.syntronic.client.thread.ORCThreadTejasInv.retrieveOracleTejas(ORCThreadTejasInv.java:125)
at com.syntronic.client.thread.ORCThreadTejasInv.run(ORCThreadTejasInv.java:84)
at java.lang.Thread.run(Thread.java:745)
Anyone can help on why the date is unparseable? and how to convert it to a proper sql timestamp? thank you
Your fromFormat format specifier is
dd/MM/yyyy hh:mm
but should be
dd/MM/yyyy HH:mm
And change the toFormat to yyyy-MM-dd HH:mm:ss.SSSSSS
Then your parse code should change from
date2 = toFormat.parse(test);
to
date2 = fromFormat.parse(test);
System.out.println(toFormat.format(date2));
And I get the output
2014-10-08 04:59:00.000000
Please use following code it will serve your need
String test = "8/10/2014 16:59";
Date date2 = null;
SimpleDateFormat fromFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
try
{
date2 = fromFormat.parse(test);
Timestamp tt = new Timestamp(date2.getTime());
System.out.println(tt);
} catch (ParseException ex)
{
date2 = null;
}
When you parse a date-string that looks like this:
String test = "8/10/2014 16:59";
you're using 24-hours format (16:59) you should use HH instead of hh.
See the following code snippet:
DateFormat fromFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
fromFormat.setLenient(false);
Date date2 = null;
try {
date2 = fromFormat.parse(test);
System.out.println("date2 = " + date2); // prints date2 = Wed Oct 08 16:59:00 PDT 2014
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So you have a String, and you want to parse it as a Date... Let's see if this example helps you:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateConverter
{
public static void main(String[] args) {
String test = "8/10/2014 16:59";
SimpleDateFormat sdf1 = new SimpleDateFormat("d/MM/yyyy HH:mm"),
sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/*
'sdf1' will be used to parse your input string as a date
'sdf2' will be used to output a string with your desired date format
*/
Date d;
String formatted_date;
try {
// Parse the string to a date, using the defined format
d = sdf1.parse(test);
// Now, format the date with 'sdf2' and store it in a string
formatted_date = sdf2.format(d);
System.out.println(formatted_date); // The output is: 2014-10-08 16:59:00
} catch(ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
}
}
}
Was able to fix it using the code below:
DateFormat fromFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date2 = null;
String def = perRow[cnt].replaceAll("8", "08");
try {
date2 = fromFormat.parse(def);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long tsTime1 = date2.getTime();
java.sql.Timestamp sqlDate2 = new java.sql.Timestamp(tsTime1);
sql_statement.setTimestamp(2, sqlDate2);
Of course, I don't know if this is the correct or proer way to it as:
1. replace the sting with correct day 'dd'
2. parse to date format
3. convert to long
4. convert to sql date
Anyone knows a better way or idea, thread is open for comments. thank you.
You can convert it using java.sql.Timestamp. Here is a snippet:
String strDate = "15/07/1989 15:30";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date date = format.parse(strDate);
System.out.println(date);
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp);
And the output will be:
Sat Jul 15 15:30:00 IST 1989
1989-07-15 15:30:00.0
Simple!
First parse fromDate then format in toDate pattern.
toFormat.format(fromFormat.parse(test));

Java: Issue in SimpleDateFormat class

I am trying to convert a date string of format dd.MM.YYYY into date object as following:
String start_dt = "01.01.2011";
DateFormat formatter = new SimpleDateFormat("dd.MM.YYYY");
Date date = (Date)formatter.parse(start_dt);
System.out.print("Date is : "+date);
But I am getting this result Date is : Sun Dec 26 00:00:00 MST 2010
I tried it in different ides and even on compileonline.com , still same result.
So Am I doing anything wrong here, because its not suppose to behave like this.
Please help.
The pattern for year is incorrect. You need to say:
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
The correct representation is yyyy
String start_dt = "01.01.2011";
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
Date date = null;
try {
date = (Date)formatter.parse(start_dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("Date is : "+date);
public static void main(String[] args) {
try {
String start_dt = "01.01.2011";
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
Date date = (Date)formatter.parse(start_dt);
System.out.print("Date is : "+date);
} catch (ParseException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
you should learn about DateFormat from here link1 and link2, you will realize that your code should be like that (year should be written in small letters).
String start_dt = "01.01.2011";
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
Date date = (Date)formatter.parse(start_dt);
System.out.print("Date is : "+date);

Categories

Resources