Convert String to Date with Milliseconds - java

I know that there many subject of how to convert from String to Date, I'm using 'SimpleDateFormat' and i have a string that contains (Year, Month, Day , Hour, Minute, second, Milliseconds) but when I'm using the 'SimpleDateFormat' the Milliseconds is not set
here the code and the output:
import java.text.SimpleDateFormat;
import java.util.Date;
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date dateFormatter = formatter.parse(strDate);
System.out.println(dateFormatter);
Output:
Thu Aug 27 10:06:07 WAT 2020
I want the result in type Date

The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.
You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.
If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:
System.out.println(formatter.format(dateFormatter));
outputs 2020-08-27T10:06:07.413

You can use:
String strDate = "2020-08-27T10:06:07.413"
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
DateTime datetimeDF = formatter.parseDateTime(strDate);
String text = formatter.print(datetimeDF);
System.out.println(text);
Or you can use java.time:
String strDate = "2020-08-27T10:06:07.413"
LocalDateTime ldate = LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
and use the object ldate as you want.

Update (based on OP's comment):
You have mentioned: Thanks that was realy heplful I've allready tried the java.util but i could not set the date in the database using LocalDateTime that's why I'm using Date
You've to use PreparedStatement#setObject to set LocalDate into the database table e.g.
LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate();
st.close();
Original answer:
Given below is the toString implementation of java.util.Date:
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == BaseCalendar.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
As you can see in this implementation, it doesn't include milliseconds and therefore if you print date as in the following code, you will get what the Date#toString returns and thus, you won't see milliseconds in the output.
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date= formatter.parse(strDate);
System.out.println(date);
I assume that you already know that System.out.println(obj) prints the string returned by obj.toString().
How can you get output in a custom format?
You have two options:
Recommended option: Use a date-time formatter e.g. SimpleDateFormat as shown below:
String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = formatter.parse(strDate);
System.out.println(date);
String dateStr = formatter.format(date);
System.out.println(dateStr);
Override toString implementation of Date by creating a custom class by extending java.util.Date. Although it's an option, I never recommend this to do.
Finally, a piece of advice:
Stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.

Related

How can i convert String to Date when it has "TRT" in it

String sDate = "06.08.2020" // 06 day 08 month 2020 is year
This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
And it does convert the string to date as this.
LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020
Now i need to convert it like the first date 06.08.2020.
But i can't use date as input. Because i get it from JTable so i get it as String.
So i tryed this code.
String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);
But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.
So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter);
I cant see where is the problem.
I cannot reproduce the behaviour you describe. The following code worked fine for me:
import java.util.*;
import java.text.*;
public class MyClass {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = "06.08.2020";
Date date1 = sdf.parse(date);
String result = sdf.format(date1);
System.out.println("Date = " + result);
}
}
Output: Date = 06.08.2020
That being said, if at all possible you should switch to the new java.time.* API.
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.
Can I format the Date object (i.e. date) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00

my Date Util formatter does not return my intended date format need help, [duplicate]

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Change format date in Java does not work correctly [duplicate]

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Add colon to 24 hour time in Java?

I have a date in the format MM/DD/YYYY and time in the format HHMM (24 hour time w/o the colon). Both of these strings are in an array. I would like to store this as one string - maybe something like "MM-DD-YYYY HH:MM" - and then be able to convert it to a written date like "January 1, 2014 16:15" when I am showing it to the user. How can I do this?
This is the code that I have:
String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);
However this is what I get: "Sun Dec 29 23:01:00 EST 2013"
The output I am looking for is: "December 29, 2013 23:01"
SimpleDateFormat is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.
You specify the 2 formats as follows:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):
String[] array = { "12/31/2013", "1230" };
You would have to set these parsed dates in a Calendar instance:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
Finally format your date using the same SimpleDateFormat
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");
Here is the complete working code:
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
String[] array = { "12/31/2013", "1230" };
try {
Date date = dateFormat.parse(array[0]);
Date time = timeFormat.parse(array[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());
SimpleDateFormat newFormat = new SimpleDateFormat(
"MMMM dd, yyyy 'at' hh:mm");
String datePrint = newFormat.format(cal.getTime());
System.out.println(datePrint);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output:
December 31, 2013 at 12:30
Unfortunately, none of the existing answers has mentioned the root cause of the problem which is as follows:
You have used D (which specifies Day in year) instead of d (Day in month).
You have used Y (which specifies Week year) instead of y (Year).
Learn more about it at the documentation page. Now that you have understood the root cause of the problem, let's focus on the solution using the best standard API of the time.
java.time
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
I would solve it in the following steps:
Parse the date string into LocalDate.
Parse the time string into LocalTime.
Combine the objects of LocalDate and LocalTime to obtain an object of LocalDateTime.
Format the object of LocalDateTime into the desired pattern.
Demo using the modern API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// 1. Parse the date string into `LocalDate`.
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dateParser);
// 2. Parse the time string into `LocalTime`.
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
LocalTime time = LocalTime.parse("1615", timeParser);
// 3. Combine date and time to obtain an object of `LocalDateTime`.
LocalDateTime ldt = date.atTime(time);
// 4. Format the object of `LocalDateTime` into the desired pattern.
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
String output = dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
January 1, 2014 16:15
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can use java.text.DateFormat class to convert date to string(format method), and string to date(parse method).
You can use SimpleDateFormat both to parse Strings into dates and to format Dates back into Strings. Here's your example:
SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
String dateString = "05/27/2014 23:01";
Date parsedDate = parser.parse(dateString);
String formattedDateString = formatter.format(parsedDate);
System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");
When I run this, I get:
Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'
Goal
Convert String to Date with the format you have it in
Output that date as a String in the format you want
Code:
String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date " +df);
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));
Output:
date Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
you can use this >>
String s = sd.format(d);
String s1 = sd1.format(d);
Here Is the full code >>
import java.text.SimpleDateFormat;
import java.util.Date;
public class dt {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");
String s = sd.format(d);
String s1 = sd1.format(d);
System.out.println(s +" "+ s1);
}
}
You should have bothered to do a bit of searching before posting. StackOverflow.com has many questions and answers like this already.
But for the sake of posterity, here's some example code using the Joda-Time 2.3 library. Avoid the java.util.Date/Calendar classes bundled with Java as they are badly designed and implemented. In Java 8, continue to use Joda-Time or switch to the new java.time.* classes defined by JSR 310: Date and Time API. Those new classes were inspired by Joda-Time but are entirely re-architected.
Joda-Time has many features aimed at formatting output. Joda-Time offers built-in standard (ISO 8601) formats. Some classes render strings with format and language appropriate to the host computer's locale, or you can specify a locale. And Joda-Time lets you define your own funky formats as well. Searching for "joda" + "format" will get you many examples.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String input = "05/27/2014" + " " + "23:01";
Parse that string…
// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );
Ideally you would store the values in an appropriate date-time format in a database. If not possible, then store as a string in ISO 8601 format, set to UTC/GMT (no time zone offset).
// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.
Do your business logic and storage in UTC generally. Switch to local time zones and localized formatting only in the user-interface portion of your app.
// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );
When run…
input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM

Convert UTC into Local Time on Android

In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time.
That is where ever we use this the app needs to show the local time. How to I do this?
Here is some Code I have tried:
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);
Assume aDate contains Jul 16, 2013 12:08:59 AM
Here's my attempt:
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Also notice the "a" for the am/pm marker...
I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.
But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.
Now the code is:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
String aDate = "Jul 16, 2013 12:08:59 AM";
String formattedDate = LocalDateTime.parse(aDate, formatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault())
.format(formatter);
System.out.println(formattedDate);
Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints
Jul 16, 2013 02:08:59 AM
Further points:
Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.
1.Local to UTC Converter
public static String localToUTC(String dateFormat, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
2. UTC to Local Converter
public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
sdfOutPutToSend.setTimeZone(TimeZone.getDefault());
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn; }
//your UTC time var
long time = UTCtime;
//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));
//use the value
long localTime = timeFormat.toMillis(true);
Use the following code.
TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);
//The code you use
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);
This should work.
This is how i do it on android Build.VERSION.SDK_INT < 26
int offset = TimeZone.getDefault().getRawOffset();
String str_date='20:30 12-01-2021';
DateFormat formatter = new SimpleDateFormat("HH:mm dd-MM-yyy",Locale.US);
Date date = formatter.parse(str_date);
long utcTime = date.getTime() + (3600000*3);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.US);
String dateStr = sdf.format(utcTime + offset);
System.out.println(dateStr);
As my server sends the time with -3 timezone i have to add (3600*3) to getTime and i save it into utcTime, this way utcTime is in UTC. And then i add to utcTime the offset of the phone current timezone.
In my case as my timezone is -3 its prints:
20:30 12/01/2021
But if i change my time zone the date also changes.
Use this code:
public static String stringDateWithTimezone(Date date, String pattern, TimeZone timeZone) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.US);
if (timeZone != null) {
simpleDateFormat.setTimeZone(timeZone);
}
return simpleDateFormat.format(date);
} catch (Exception e) {
Timber.e(e);
return null;
}
}
call in another class:
String dateUtc = DateUtil.stringDateWithTimezone(new Date(), "yyyy-MM-dd hh:mm:ss", TimeZone.getTimeZone("UTC"));

Categories