How can I convert milliseconds to a time and date string and format it correctly like the user expects it to be?
I did the following:
((SimpleDateFormat)DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.getDefault())).format(new Date(Long.parseLong(timeInMilliseconds)));
Which seems to work, but I only get the date with this method.
Edit:
To clearify, I need to get the time/date pattern from system somehow to give each user his common format
Now I combined your solutions with mine and it seems to work like I expect.
private String getFormattedDateTimeString(Context context, String timeInMilliseconds) {
SimpleDateFormat dateInstance = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
SimpleDateFormat timeInstance = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.getDefault());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(timeInMilliseconds));
String date = dateInstance.format(calendar.getTime());
String time = timeInstance.format(calendar.getTime());
return date + " " + time;
}
Why the hell do I get downvotes for this question???
All the other answers are missing the point that the string representation of the date-time needs to be localized.
Joda-Time
The Joda-Time 2.3 library makes this work much easier.
Joda-Time leverages a java.util.Locale to determine proper formatting of a date-time's string representation. The DateTimeFormat class offers an option for "style" pattern as a way of generating a DateTimeFormatter. You specify a two character style pattern. The first character is the date style, and the second character is the time style. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
If you do not specify a Locale or time zone, the JVM's default will be used.
Locale
To create a java.util.Locale, you need:
Language code (either, see combined list)
ISO 639 alpha-2
ISO 639 alpha-3
Country Code (either)
ISO 3166 alpha-2 country code
UN M.49 numeric-3 area code
Example Code
// Simulate input.
long millisecondsSinceEpoch = DateTime.now().getMillis();
// Proceed with a 'long' value in hand.
DateTime dateTimeUtc = new DateTime( millisecondsSinceEpoch, DateTimeZone.UTC );
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Riyadh" );
DateTime dateTimeRiyadh = dateTimeUtc.withZone( timeZone );
// 'ar' = Arabic, 'SA' = Saudi Arabia.
java.util.Locale locale = new Locale( "ar", "SA" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).withZone( timeZone );
String output = formatter.print( dateTimeUtc );
Dump to console…
System.out.println( "millisecondsSinceEpoch: " + millisecondsSinceEpoch );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeRiyadh: " + dateTimeRiyadh );
System.out.println( "output: " + output );
When run…
millisecondsSinceEpoch: 1392583624765
dateTimeUtc: 2014-02-16T20:47:04.765Z
dateTimeRiyadh: 2014-02-16T23:47:04.765+03:00
output: 16 فبراير, 2014 AST 11:47:04 م
Leaving your code as is, just change:
Instead of
getDateInstance
try
getDateTimeInstance
Or, you'd better use:
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String datetime = fmt.format(cal.getTimeInMillis());
Use this...
String dateFormat = "dd/MM/yyyy hh:mm:ss.SSS";
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
String formatedDate = formatter.format(calendar.getTime());
Try this
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");// you can rearange it as you like
cal.setTimeInMillis(timeInMilliseconds); //convert the time in milli to a date
String date = format.format(cal.getTime());// here you get your time formated
Why on earth do you want to use a calendar object???? It's just a waste of resources.
// Create a DateFormatter object for displaying date in specified format.
DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formatedDate = myDateFormat.format(new Date(timeInMilliseconds));
Related
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());
I want to get the date in 24 hours format but can't find anything.
i tried this with no luck:
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Calendar.getInstance().getTime()));
but it prints
28/05/14 03:57 PM
instead of
28/05/14 15:57
how can i print the hour without the AM/PM and in 24 hours format?
DateFormat.getDateTimeInstance() can also have three arguments. The third argument specifies the region where certain customs like time formats are common (if 24-hour-style in most countries or rather am/pm-style like in US).
By choosing an explicit locale you can control the behaviour of your format-object in a locale-dependent way. Internally Java will choose the right format pattern for you given the informations about date style, time style and locale.
If this is not sufficient you might consider SimpleDateFormat instead. Then you yourself decide which exact format pattern to choose, but this is fixed then. You might also consider a combination of both approaches if you are not satisfied with what Java sees as right format for given locale but also want to have a localized solution:
DateFormat df;
if (locale.equals(myLocale)) {
df = new SimpleDateFormat("dd/MM/yy HH:mm"); // yy for 2-digit-year, not YY!
} else {
// general solution for other locales
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, myLocale);
}
The answer by Meno Hochschild is correct.
FYI, here is the same kind of solution but using Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Specify a time zone rather than rely on default.
DateTime now = DateTime.now( timeZone );
Generate a String representation in the sensible ISO 8601 format. This standard uses 24-hour clock.
String outputIso = now.toString();
Generate a String representation in a localized format.
java.util.Locale locale = java.util.Locale.CANADA_FRENCH;
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( locale );
String outputQuébécois = formatter.print( now );
Generate exactly the format you specified.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yy HH:mm" ); // See note about year in answer by Meno Hochschild.
String output = formatter.print( now );
You need to use a SimpleDateFormat object.
The string you want is "dd/MM/YY HH:mm"
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm");
Date myFormattedDate = dateFormat.parse(myUnformattedDate);
System.out.println(myFormattedDate.toString());
String dateTimePattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat sdf = new SimpleDateFormat(dateTimePattern);
Date startTime = sdf.parse("2014-03-14 04:16:58.666");
System.out.println(startTime);
Output
Fri Mar 14 04:16:58 CDT 2014
Why is not printing milliseconds?
The problem here is not that the milliseconds are not getting parsed, your startTime includes the milliseconds you have provided. The problem is that they are not getting printed.
You need to format your output if you want something other than the default format from Date#toString():
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
You can use your SimpleDateFormat to format your output too, which will give you milliseconds:
System.out.println(sdf.format(startTime));
You are printing startTime directly (e.g. the toString() from java.util.Date); if you want your output to match your specified DateFormat you could do -
String dateTimePattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat sdf = new SimpleDateFormat(dateTimePattern);
Date startTime = sdf.parse("2014-03-14 04:16:58.666");
System.out.println(sdf.format(startTime)); // <-- use the DateFormat.
Which will output
2014-03-14 04:16:58.666
The other answers are correct.
Avoid j.u.Date
You would have simpler code and none of that confusion if you used Joda-Time (or java.time package in Java 8) rather than the notoriously troublesome java.util.Date & .Calendar & java.text.SimpleDateFormat classes bundled with Java.
Joda-Time
Joda-Time has built-in automatic parsers for ISO 8601 formats. Your format would work if you replaced that space with a T.
Example code using Joda-Time 2.3…
String inputRaw = ( "2014-03-14 04:16:58.666" );
String input = inputRaw.replace( " ", "T" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( input, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 2014-03-14T04:16:58.666
dateTime: 2014-03-14T04:16:58.666+01:00
dateTimeUtc: 2014-03-14T03:16:58.666Z
I have a date string in this format:
String fieldAsString = "11/26/2011 14:47:31";
I am trying to convert it to a Date type object in this format: "yyyy.MM.dd HH:mm:ss"
I tried using the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date newFormat = sdf.parse(fieldAsString);
However, this throws an exception that it is an Unparsable date.
So I tried something like this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date)
However, this new format is now in the 'String' format but I want my function to return the new formatted date as a 'Date' object type. How would I do this?
Thanks!
You seem to be under the impression that a Date object has a format. It doesn't. It sounds like you just need this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
(You should consider specifying a locale and possibly a time zone, mind you.)
Then you've got your Date value. A format is only relevant when you later want to convert it to text... that's when you should specify the format. It's important to separate the value being represent (an instant in time, in this case) from a potential textual representation. It's like integers - there's no difference between these two values:
int x = 0x10;
int y = 16;
They're the same value, just represented differently in source code.
Additionally consider using Joda Time for all your date/time work - it's a much cleaner API than java.util.*.
The answer by Jon Skeet is correct and complete.
Internal to java.util.Date (and Date-Time seen below), the date-time value is stored as milliseconds since the Unix epoch. There is no String inside! When you need a textual representation of the date-time in a format readable by a human, either call toString or use a formatter object to create a String object. Likewise when parsing, the input string is thrown away, not stored inside the Date object (or DateTime object in Joda-Time).
Joda-Time
For fun, here is the (better) way to do this work with Joda-Time, as mentioned by Mr. Skeet.
One major difference is that while a java.util.Date class seems to have a time zone, it does not. A Joda-Time DateTime in contrast does truly know its own time zone.
String input = "11/26/2011 14:47:31";
// From text to date-time.
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Time zone intended but unrecorded by the input string.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" ).withZone( timeZone );
// No words in the input, so no need for a specific Locale.
DateTime dateTime = formatterInput.parseDateTime( input );
// From date-time to text.
DateTimeFormatter formatterOutput_MontréalEnFrançais = DateTimeFormat.forStyle( "FS" ).withLocale( java.util.Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) );
String output = formatterOutput_MontréalEnFrançais.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime as milliseconds since Unix epoch: " + dateTime.getMillis() );
System.out.println( "dateTime in UTC: " + dateTime.withZone( DateTimeZone.UTC ) );
System.out.println( "output: " + output );
When run…
input: 11/26/2011 14:47:31
dateTime: 2011-11-26T14:47:31.000-10:00
dateTime as milliseconds since Unix epoch: 1322354851000
dateTime in UTC: 2011-11-27T00:47:31.000Z
output: samedi 26 novembre 2011 19:47
Search StackOverflow for "joda" to find many more examples.
I want to convert a java.util.Date object to a String in Java.
The format is 2010-05-30 22:15:52
Convert a Date to a String using DateFormat#format method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)
//Formats a date/time into a specific pattern
DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
tl;dr
myUtilDate.toInstant() // Convert `java.util.Date` to `Instant`.
.atOffset( ZoneOffset.UTC ) // Transform `Instant` to `OffsetDateTime`.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String.
.replace( "T" , " " ) // Put a SPACE in the middle.
2014-11-14 14:05:09
java.time
The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.
First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Conversions to/from java.time are performed by new methods added to the old classes.
Instant instant = myUtilDate.toInstant();
Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.
String output = instant.toString();
2014-11-14T14:05:09Z
For other formats, you need to transform your Instant into the more flexible OffsetDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
odt.toString(): 2020-05-01T21:25:35.957Z
See that code run live at IdeOne.com.
To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.
Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.
To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]
To generate a formatted String, do the same as above but replace odt with zdt.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " );
2014-11-14 14:05:09
If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ); // Data-loss: Dropping any fractional second.
Apply that formatter by passing the instance.
String output = zdt.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Altenative one-liners in plain-old java:
String.format("The date: %tY-%tm-%td", date, date, date);
String.format("The date: %1$tY-%1$tm-%1$td", date);
String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);
String.format("The date and time in ISO format: %tF %<tT", date);
This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.
Slightly more repetitive but needs just one statement.
This may be handy in some cases.
Why don't you use Joda (org.joda.time.DateTime)?
It's basically a one-liner.
Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
// output: 2014-11-14 14:05:09
It looks like you are looking for SimpleDateFormat.
Format: yyyy-MM-dd kk:mm:ss
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
public static String formateDate(String dateString) {
Date date;
String formattedDate = "";
try {
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formattedDate;
}
If you only need the time from the date, you can just use the feature of String.
Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );
This will automatically cut the time part of the String and save it inside the timeString.
Here are examples of using new Java 8 Time API to format legacy java.util.Date:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
.withZone(ZoneOffset.UTC);
String utcFormatted = formatter.format(date.toInstant());
ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
// gives the same as above
ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
// 2011-12-03T10:15:30+01:00[Europe/Paris]
String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).
List of predefined fomatters and pattern notation reference.
Credits:
How to parse/format dates with LocalDateTime? (Java 8)
Java8 java.util.Date conversion to java.time.ZonedDateTime
Format Instant to String
What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh
- HH refers to 24h time format
- hh refers to 12h time format
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
From Convert Date to String in Java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = "2010-05-30 22:15:52";
java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not
logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());