The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?
String date = "2010-08-25";
String time = "00:00";
Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?
private static Date date(final String date,final String time) {
final Calendar calendar = Calendar.getInstance();
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String[] hm = time.split(":");
int hour = Integer.parseInt(hm[0]);
int minute = Integer.parseInt(hm[1]);
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d = calendar.getTime();
String dateString= dateFormat.format(d);
Date result = null;
try {
result = (Date)dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
What's wrong in this code?
You seem to be expecting the returned Date object to know about the format you've parsed it from - it doesn't. It's just an instant in time. When you want a date in a particular format, you use SimpleDateFormat.format, it's as simple as that. (Well, or you use a better library such as Joda Time.)
Think of the Date value as being like an int - an int is just a number; you don't have "an int in hex" or "an int in decimal"... you make that decision when you want to format it. The same is true with Date.
(Likewise a Date isn't associated with a specific calendar, time zone or locale. It's just an instant in time.)
How did you print out the return result? If you simply use System.out.println(date("2010-08-25", "00:00") then you might get Sat Sep 8 00:00 PDT 2010 depending on your current date time format setting in your running machine. But well what you can do is:
Date d = date("2010-08-25", "00:00");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d));
Just curious why do you bother with this whole process as you can simple get the result by concatenate your initial date and time string.
just use SimpleDateFormat class
See
date formatting java simpledateformat
The standard library does not support a formatted Date-Time object.
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT
2010". But I expected to get the date in the following format
"yyyy-MM-dd HH:mm".
The standard Date-Time classes do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:
For the modern Date-Time API: java.time.format.DateTimeFormatter
For the legacy Date-Time API: java.text.SimpleDateFormat
About java.util.Date:
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date(); // In your case, it will be Date date = date("2010-08-25", "00:00");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
// sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); // For a timezone-specific value
String strDate = sdf.format(date);
System.out.println(strDate);
Your function, Date date(String, String) is error-prone.
You can simply combine the date and time string with a separator and then use SimpleDateFormat to parse the combined string e.g. you can combine them with a whitespace character as the separator to use the same SimpleDateFormat shown above.
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
Note that using a separator is not a mandatory requirement e.g. you can do it as sdf.parse(date + time) but for this, you need to change the format of sdf to yyyy-MM-ddHH:mm which, although correct, may look confusing.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Date date = date("2010-08-25", "00:00");
String strDate = sdf.format(date);
System.out.println(strDate);
}
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
}
Output:
2010-08-25 00:00
ONLINE DEMO
Switch to java.time API.
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time 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) {
LocalDateTime ldt = localDateTime("2010-08-25", "00:00");
// Default format i.e. the value of ldt.toString()
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ENGLISH);
String strDate = dtf.format(ldt);
System.out.println(strDate);
}
private static LocalDateTime localDateTime(final String date, final String time) {
return LocalDateTime.of(LocalDate.parse(date), LocalTime.parse(time));
}
}
Output:
2010-08-25T00:00
2010-08-25 00:00
ONLINE DEMO
You must have noticed that I have not used DateTimeFormatter for parsing the String date and String time. It is because your date and time strings conform to the ISO 8601 standards. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
Learn more about 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.
I'm surprise you are getting different date outputs on the different computers. In theory, SimpleDateFormat pattern "H" is supposed to output the date in a 24h format. Do you get 11:45pm or 11:45am?
Although it should not affect the result, SimpleDateFormat and Calendar are Locale dependent, so you can try to specify the exact locale that you want to use (Locale.US) and see if that makes any difference.
As a final suggestion, if you want, you can also try to use the Joda-Time library (DateTime) to do the date manipulation instead. It makes it significantly easier working with date objects.
DateTime date = new DateTime( 1991, 10, 13, 23, 39, 0);
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm").format( date.toDate());
DateTime newDate = DateTime.parse( dateString, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
Related
I have date which is in the format of(example) Date = 2023-01-09T23:51:44.595Z
and I have utcOffset String utcOffset = "UTC +6"
I want output as 2023-01-10T05:51:44.595Z in Date format.
How to achieve this??
I should add UTC offset to existing date.
Tried this:
public static void main(String[] args) throws ParseException {
String rawDate = "2023-01-09T23:51:44.595Z";
String utcOffset = "UTC +6";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
Date date = (Date) formatter.parse(rawDate);
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
String v = formatter1.format(date);
System.out.println("Original raw date::::::::::"+v);
System.out.println("utcOffset::::::::::"+utcOffset);
Date triggerTime = date;
String onlyHoursAndMin = StringUtils.strip(utcOffset, "UTC ");
String[] split = onlyHoursAndMin.split(":");
int hours = Integer.parseInt("0");
int minutes = Integer.parseInt("0");
if (split.length == 2) {
hours = Integer.parseInt(split[0]);
minutes = Integer.parseInt(split[1]);
} else if (split.length == 1) {
hours = Integer.parseInt(split[0]);
minutes = Integer.parseInt("0");
}
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTime(triggerTime);
calendar.add(Calendar.HOUR_OF_DAY, hours);
calendar.add(Calendar.MINUTE, minutes);
Date s = calendar.getTime();
SimpleDateFormat utcFormatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
String newDate = utcFormatter1.format(s);
System.out.println("Date in string format::::::::::::::"+newDate);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
Date aaa = format1.parse(newDate);
String bbb = format2.format(aaa);
System.out.println(":::::::::::::"+aaa);
System.out.println("Date in correct format::::::::::::::"+format2.format(aaa));
}
but finale Date format is Tue Jan 10 05:51:44 IST 2023 which is not expected.
and when build I am getting below error as well:
Forbidden method invocation: java.util.Calendar#getInstance(java.util.TimeZone) [Uses default locale or time zone]
I would suggest to move away from the legacy API (java.util.Date, java.util.Calendar, etc.), it is cumbersome and error prone. Since java 8 the modern date-time API, java.time, is available. With it the task would be quite trivial.
String date = "2023-01-09T23:51:44.595Z";
OffsetDateTime oldDateTime = OffsetDateTime.parse(date);
System.out.println("old - " + oldDateTime);
ZoneOffset offset = ZoneOffset.ofHours(6);
OffsetDateTime newDateTime = oldDateTime.withOffsetSameInstant(offset);
System.out.println("new - " + newDateTime);
Prints time - 2023-01-10T05:51:44.595+06:00.
Note that it ends with +06:00, not Z. Z at the end of a date-time string means Zulu, which indicates that the time is in UTC - What is the Z ending on date strings like 2014-01-01T00:00:00.588Z. Since resulting time is UTC + 6 hours, a date sting 2023-01-10T05:51:44.595Z would be incorrect.
java.time
The java.util date-time API and their corresponding parsing/formatting type, SimpleDateFormat are outdated and error-prone. In March 2014, the modern Date-Time API was released as part of the Java 8 standard library which supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time, the modern date-time API.
Solution using java.time
java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date-time string, 2023-01-09T23:51:44.595Z which can be directly parsed into an OffsetDateTime.
Your offset string is not in the ISO 8601 standard format. The standard format is +/-HH:mm:ss or Z which refers to +00:00 offset. In most cases, you will see +/-HH:mm e.g. +06:00. You can choose any basic string manipulation technique to get the hours and minutes from your string and create a ZoneOffset instance using them. I have used one which I have found easy to do.
The rest of the code is straightforward.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
class Main {
public static void main(String[] args) {
String strDateTime = "2023-01-09T23:51:44.595Z";
String utcOffset = "UTC +6";
int offsetHour = Integer.parseInt(utcOffset.replaceAll("[^0-9+-]", ""));
ZoneOffset zoneOffset = ZoneOffset.ofHours(offsetHour);
OffsetDateTime odtGiven = OffsetDateTime.parse(strDateTime);
OffsetDateTime odtDesired = odtGiven.withOffsetSameLocal(zoneOffset)
.withOffsetSameInstant(zoneOffset.UTC);
System.out.println(odtDesired);
}
}
Output:
2023-01-09T17:51:44.595Z
Note that 2023-01-10T05:51:44.595Z does not make sense without am/pm marker as you mean 05:51:44.595 pm. You can use a DateTimeFormatter to format the above output in your desired way.
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
I liked the alternative way suggested by Ole V.V. to parse the offset string. Given below is the solution based on his suggestion:
class Main {
public static void main(String[] args) {
String strDateTime = "2023-01-09T23:51:44.595Z";
String utcOffset = "UTC +6";
DateTimeFormatter offsetFormatter = new DateTimeFormatterBuilder()
.appendLiteral("UTC ")
.appendOffset("+H:mm", "+0")
.toFormatter(Locale.ROOT);
ZoneOffset zoneOffset = offsetFormatter.parse(utcOffset, ZoneOffset::from);
// Rest of the lines are the same as the above code
}
}
ONLINE DEMO
public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
return date.toString("h:mm aa");
} catch (Exception e) {
return null;
}
}
main(){
print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}
I am trying to convert given date-time in UTC format using joda date time it's giving wrong time it's given one hour before please help me what I am doing wrong.
The desired result is in London time, so 8:31 AM in this case.
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class CurrentUtcDate {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC Time is: " + dateFormat.format(date));
}
}
Output
UTC Time is: 22-01-2018 13:14:35
You can check here https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java
As you need to you use Joda DateTime, you need to use formatter of Joda.
You are returning date with pattern "h:mm aa" so I assume you need to extract time from the date.
Below code should work:
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class MyDateCoonverter {
public static void main(String a[]) {
System.out.println(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"));
}
public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt = formatter.parseDateTime(dateTime);
return dt.toString("h:mm aa", Locale.ENGLISH);
}
}
It gives output as:
7:31 AM
If you don't want to use any third party library & still want to extract only time from date, you can use Java's LocalTime.
If you are using Java 8 or newer, you should not use java.util.Date (deprecated) or Joda Time (replaced by the new DATE API of Java 8 with java.time package) :
public static void main(String[] args) {
String date = "2020-04-09T07:31:16Z";
String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
System.out.println(formatedDate); //print "7:31 AM"
}
}
First, don’t handle date and time as strings in your program. Handle them as proper date-time objects. So but for all but the simplest throw-away programs you should not want a method that converts from a string in UTC to a string in London time in a different format.
So when you accept string input, parse into a DateTime object:
String stringInput = "2020-04-09T07:31:16Z";
DateTime dt = DateTime.parse(stringInput);
System.out.println("Date-time is: " + dt);
Output so far is:
Date-time is: 2020-04-09T07:31:16.000Z
I am exploiting the fact that your string is in ISO 8601 format, the default for Joda-Time, so we need no explicit formatter for parsing it.
Not until you need to give string output, convert your date and time to the desired zone and format into the desired string:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime outputDateTime = dt.withZone(zone);
String output = outputDateTime.toString("h:mm aa");
System.out.println("Output is: " + output);
Output is: 8:31 AM
What went wrong in your code
Z in single quotes in your format pattern string is wrong. Z in your input string is an offset of 0 from UTC and needs to be parsed as an offset, or you are getting an incorrect result. Never put those quotes around Z.
withZoneRetainFields() is the wrong method to use for converting between time zones. The method name means that the date and hour of day are kept the same and only the time zone changed, which typically leads to a different point in time.
What happened was that your string was parsed into 2020-04-09T07:31:16.000+01:00, which is the same point in time as 06:31:16 UTC, so wrong. You next substituted the time zone to UTC keeping the time of day of 07:31:16. This time was then formatted and printed.
Do consider java.time
As Fabien said, Joda-Time has later been replaced with java.time, the modern Java date and time API. The Joda-Time home page says:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
Links
Wikipedia article: ISO 8601
Joda-Time home
I am trying to convert the string to date and i want that date to be in this format 'yyyy-MM-d HH:mm:ss' and i no how to get this format in string my question is i want to get Date in above format not as string but as 'Date '?
i am doing in this way
for(int k=0;k<12;k++)//for the months
{
//i have added if condtion for the months with 31 and 30 and 28 days
Calendar dateFromCal = Calendar.getInstance();
dateFromCal.setTime(date);
dateFromCal.set(year, k, 1, 0, 0, 0);
Calendar dateToCal = Calendar.getInstance();
dateToCal.setTime(date);
dateToCal.set(year, k, 31, 23, 59, 59);
//i have set the date format as 'yyyy:MM:dd HH:mm:ss'
dateFrom = dateFormat.format(dateFromCal.getTime());
dateTo = dateFormat.format(dateToCal.getTime());
fromdate = (Date)dateFormat.parse(dateFrom);
todate = (Date)dateFormat.parse(dateTo);
}
by using above code i am getting the date in the following format
Sat Nov 01 00:00:00 GMT 2014
but i want the date format to be as
2014-11-01 00:00:00
NOTE:I want this result as Date not as String
Please give me solution for this
Thanks....
i want to get Date in above format not as string but as 'Date '?
You're asking for a Date in a particular format - that's like saying "I want an int in hex format." A Date doesn't have a format - it's just an instant in time. It doesn't know about a calendar system or a time zone - it's just a number of milliseconds since the Unix epoch. If you want a formatted value, that's a string.
You should probably just keep the Date as it is, and format it later on, closer to the UI.
NOTE:I want this result as Date not as String
Short answer: It is NOT possible.
Details:
A java.util.Date object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
In fact, none of the standard Date-Time classes has an attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:
For the modern Date-Time API: java.time.format.DateTimeFormatter
For the legacy Date-Time API: java.text.SimpleDateFormat
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int year = 2021;
int month = 6;
int hour = 23;
int minute = 59;
int second = 59;
LocalDateTime ldt = LocalDate.of(year, month, 1)
.with(TemporalAdjusters.lastDayOfMonth())
.atTime(LocalTime.of(hour, minute, second));
// Default format i.e. ldt#toString
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String formatted = dtf.format(ldt);
System.out.println(formatted);
}
}
Output:
2021-06-30T23:59:59
2021-06-30 23:59:59
ONLINE DEMO
Learn more about 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.
I had same problem with one API that was expecting particular format (javax.xml.datatype.XMLGregorianCalendar). In my case I solve this by the help of java 7
and
my_date.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
By doing so you can get your final result for date with 00:00:00.
This is a simple method that takes care of formatting from String to Date:
` see code below:
public XMLGregorianCalendar formatToGregorianDate(String myDate) {
//actual Date format should be "dd-MMM-yy", but SimpleDateFormat accepts only this one
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
//Date is accepted only without time or zone
date = simpleDateFormat.parse(myDate.substring(0, 10));
} catch (ParseException e) {
System.out.println("Date can't be parsed to required format!");
e.printStackTrace();
}
GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
gregorianCalendar.setTime(date);
XMLGregorianCalendar result = null;
try {
result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
//date must be sent without time
result.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
} catch (DatatypeConfigurationException e) {
System.out.println("XMLGregorianCalendar can't parse the Date format!");
e.printStackTrace();
}
return result;
}`
Maybe you'll just need to adapt it for your needs, I don't know what do you need.
FYI - Note that I'm using java.util.Date. Maybe there is better logic, but this one works for sure.
Hope it helps.
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
Sat Dec 01 00:00:00 GMT 2012
I have to convert above date into below format
2012-12-01
How can i?
i have tried with following method but its not working
public Date ConvertDate(Date date){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(date);
String result = s;
try {
date=df.parse(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
String s;
Format formatter;
Date date = new Date();
// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
Joda-Time
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 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.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.
The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time.
You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.
Moreover, most of the getter methods in Date are deprecated.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.
Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
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.