My JSON object looks like
{"iso":"2014-01-01T21:13:00.000Z","__type":"Date"}
I need to get the date from it as a date Object.
What I have tried-
String dateStr = JsonObject.getString("iso"); //output is 2014-01-01T21:13:00.000Z
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date birthDate = sdf.parse(dateStr);
but this doesnt work, firstly it prompts me to add a try/catch which I do. When the debugger comes to Date birthDate = sdf.parse(dateStr); it just skips this.
How do I get a date out of my JSON object?
Use a date format like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
to match the input string format.
For details, consult the documentation.
For example this
public static void main(String[] args) throws ParseException {
String dateStr = "2014-01-01T21:13:00.000Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date birthDate = sdf.parse(dateStr);
System.out.println(birthDate);
}
prints (actual output depends on your time zone)
Wed Jan 01 22:13:00 CET 2014
Related
I have this string: 2018-09-22 10:17:24.772000
I want to convert it to Date:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
but it shows: Sat Sep 22 10:17:24 GMT+03:30 2018
Here is what you should do instead, you are printing date object itself, you should print its format.
I will provide the code with old date api and new local date api :
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
System.out.println(dateFrom); // this is what you do
System.out.println(simpleDateFormat.format(dateFrom)); // this is what you should do
// below is from new java.time package
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
System.out.println(LocalDateTime.parse(sdate, formatter).format(formatter));
output is :
Sat Sep 22 10:30:16 EET 2018
2018-09-22 10:30:16.000000
2018-09-22 10:17:24.772000
Hope This will help you
public class Utils {
public static void main(String[] args) {
String mytime="2018-09-22 10:17:24.772000";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSSSSS");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
System.out.println(finalDate);
}
}
Looks to me like you have converted it to a Date. What is your desired result? I suspect what you are wanting to do is to create another Simple date format that shows your expected format and then use simpledateformat2.format(dateFrom)
I should also point out based on past experience that you should add a Locale to your simple date formats otherwise a device with a different language setting may not be able to execute this code
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);
So I'm getting some date objects from a web server, I know that the server has the time in GMT +1 (Berlin), how can I convert the date object, to the current phone timezone date object?
Most of the questions on stackoverflow are only about formatting within a timezone, but not actually converting like this.
I've tried this
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
calendar.setTime(timeFromServer);
Calendar calendar2 = new GregorianCalendar(TimeZone.getDefault());
calendar2.setTimeInMillis(calendar.getTimeInMillis());
WHen I print, calendar2.getTime().toString() and timeFromServer.toString() will be the same;
I used Joda time and it works. You can try with Joda time. This method will convert time from server to display format time below and change to the relevant local time
public static final String SERVER_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DISPLAY_POST_FORMAT = "HH:mm dd/MM/yyyy";
public static String convertDateStrToDisplayFormat(String timeFromServer) {
DateTimeFormatter serverFormatter = DateTimeFormat.forPattern(Constants.SERVER_FORMAT);
serverFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dateTime = DateTime.parse(timeFromServer, serverFormatter);
DateTimeFormatter pointTimeFormatter = DateTimeFormat.forPattern(Constants.POINT_TIME_FORMAT);
pointTimeFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
return pointTimeFormatter.print(dateTime)
}
I use this to convert the date from the server and convert it to current phone timezone date object
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat deviceFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",Locale.ENGLISH);
deviceFormat.setTimeZone(TimeZone.getDefault());
Date utcDate ;
Date deviceDate ;
utcDate = sourceFormat.parse(event_date);
deviceDate = deviceFormat.parse(utcDate.toString());
event_date is a String that has the server date. After this you have your converted Date on deviceDate.
java.util.Date does not use timezone, so when you try to print the string representation of the following date objects using method Date#toString(), the results are the same:
calendar2.getTime().toString()
timeFromServer.toString()
In order to test the string representation correctly with timezone, you need to use SimpleDateFormat:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
f.setTimeZone(calendar.getTimeZone());
// Date correctly printed with timezone:
System.out.println(f.parse(calendar.getTime()));
However, your conversion written in the question is correct, here's how I tested it using JUnit:
#Test
public void testDateConversion() throws ParseException {
String serverText = "2017-03-02T11:54:30.207+01:00";
SimpleDateFormat serverFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
serverFmt.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date timeFromServer = serverFmt.parse(serverText);
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
calendar.setTime(timeFromServer);
assertEquals(2017, calendar.get(Calendar.YEAR));
assertEquals(Calendar.MARCH, calendar.get(Calendar.MONTH));
assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(9, calendar.get(Calendar.HOUR_OF_DAY));
assertEquals(54, calendar.get(Calendar.MINUTE));
assertEquals(30, calendar.get(Calendar.SECOND));
assertEquals(207, calendar.get(Calendar.MILLISECOND));
SimpleDateFormat currFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
currFmt.setTimeZone(calendar.getTimeZone());
System.out.printf("server_timestamp = %d, server_date = '%s', server_str = '%s'%n",
timeFromServer.getTime(),
serverFmt.format(timeFromServer),
timeFromServer.toString());
System.out.printf("current_timestamp = %d, current_date = '%s', current_str = '%s'%n",
calendar.getTime().getTime(),
currFmt.format(calendar.getTime()),
calendar.getTime().toString());
}
Result:
server_timestamp = 1488452070207, server_date = '2017-03-02T11:54:30.207+01:00', server_str = 'Thu Mar 02 11:54:30 CET 2017'
current_timestamp = 1488452070207, current_date = '2017-03-02T09:54:30.207-01:00', current_str = 'Thu Mar 02 11:54:30 CET 2017'
See also:
SimpleDateFormat (Java Platform SE 7)
This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
Closed 6 years ago.
I have date in string object. I want to convert into Date object.
Date getDateFmString(String dateString)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse(dateString);
return convertedCurrentDate ;
}
above function returning following output.
Fri Apr 22 00:00:00 IST 2016
but I want output in this format '2016-03-01' only
function should take string only.
function should return Date object.
I have done lot of research over web, but I got solution from one Expert.
Date getDateFrmString(String dDate)
{
java.sql.Date dDate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(sDate).getTime());
return dDate;
}
this is what I want.
Change the date format from
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
to
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
Hope this works
See this example
public Class DateFormatDemo{
public static void main (String args[]) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy);
String dateInString = "01/01/2015";
try{
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
This link might help you with string to date object conversions
You are parsing with the wrong format try
String dateString="01-01-2016";
SimpleDateFormat sdfP = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdfP .parse(dateString);
String date=sdf.format(convertedCurrentDate );
System.out.println(date);
Output:
2016-01-01
DEMO1
And if you want the format to dd-MM-yyyy then no need to define seperate SimpleDateFormat object.
String dateString="01-01-2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date convertedCurrentDate = sdf.parse(dateString);
String date=sdf.format(convertedCurrentDate );
System.out.println(date);
OUTPUT:
01-01-2016
DEMO2
To format the string date you have to first parse the String to Date object using the same format of date which the String have then format it using the desired format as seen in the above code.
Date objects don't have a format. Only a String does. A Date object will be output with whatever format you tell it to be format as. It all depends on what the format of the DateFormat object is when you call .format(). Calling the toString() method on a Date object uses a DateFormat of "dow mon dd hh:mm:ss zzz yyyy".
Let's do it step by step:
You have a date as String in dd-MM-yyyy format.
You want to convert it into date. (for this you are using SimpleDateFormat)
Now you are printing the date. Question here is are you printing the converted date object or input string?
If its a date object then toString method is called of date class.
As per comment on java.util.Date class it's:
dow mon dd hh:mm:ss zzz yyyy
similar to
Fri Apr 22 00:00:00 IST 2016
So that coincides with what you get in output in the second approach. But how is that code even running is strange.
String inputStr = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(input);
Variable 'input' is not defined.
What are the possible solutions:
While printing date, convert it back to String using SimpleDateFormat as per the requirement.
Date d =new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dStr = sdf.format(dateString);
System.out.printn(dStr);
Extending class java.util.Date and override toString, but that would be a bad idea.
I cannot format a date.
dateFormat.format() accepts a Date as argument. So I created a new Date()
It says the below Date() method is deprecated, and I get the below exception while running.
exception:
Exception in thread "main" java.lang.IllegalArgumentException at
java.util.Date.parse(Date.java:598)
public class MyDate {
public static void main(String[] args) {
Date date = new Date("2012-02-16T00:00:00.000-0500");
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate); // how do I test this conversion??
}
}
My database has date of the format - 2012-02-16T00:00:00.000-0500
I need to convert it to string of the format : dd-MMM-yyyy HH:mm:ss
I'm using Java6
Thanks to #Andy Brown. In addition to what Andy Brown has answered, I'm posting the complete snippet
Complete Solution:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SampleDate {
public static void main(String[] args) throws ParseException {
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-03-16T00:00:00.000-0500");
String strDate = parseFormat.format(date);
System.out.println(strDate);
// if you get date of type 'java.sql.Date' directly from database cursor like
//rs.getDate("created_date"), just pass it directly to format()
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm:ss");
String stringDate = dateFormat.format(date);
System.out.println(stringDate);
}
}
/*
Output:
2012-03-16T01:00:00.000-0400
16-Mar-2012 01:00:00
*/
you can also convert java.util.Date to java.sql.Date like this,
String dateString = "03-11-2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = dateFormat.parse(dateString);
java.sql.Date sqlDate = new Date(date.getTime());
// set the input param type as OracleTypes.DATE and pass the input param date as sqlDate
If you want to read in the date "2012-02-16T00:00:00.000-0500" you should probably use a SimpleDateFormat to parse it like so:
DateFormat parseFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = parseFormat.parse("2012-02-16T00:00:00.000-0500");
Along with the rest of your code this writes:
16-Feb-2012 05:00:00
The parse format pattern letters are listed in the SimpleDateFormat documentation. The T is escaped with apostrophes.
This answer assumes Java 7, or you would be using the new date & time API from Java 8
I have a problem with String conversion to Date Format. Please help me. Below is my code:
String strDate = "23/05/2012"; // Here the format of date is MM/dd/yyyy
Now i want to convert the above String to Date Format like "23 May, 2012".
I am using below code but i am getting value as "Wed May 23 00:00:00 BOT 2012"
String string = "23/05/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Wed May 23 00:00:00 BOT 2012
How can i get the value as "23 May, 2012". Please help me friends....
You must render the date again.
You have the string and you parse it correctly back to a Date object. Now, you have to render that Date object the way you want.
You can use SimpleDateFormat again, changing the pattern.
Your code should then look like
String string = "23/05/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string);
String newFormat = new SimpleDateFormat("dd MMMM, yyyy").format(date);
System.out.println(newFormat); // 23 May, 2012
Use the method format() from the class SimpleDateFormat with the correct pattern.
Simple use:
SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy");
System.out.println(df.format(date));
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException{
String strDate = "23/02/2012";
Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(strDate);
String date1 = new SimpleDateFormat("dd MMMM, yyyy").format(date);
System.out.println(date1);
}
}