How to format a date in java? - java

How can change this date format "2011-09-07T00:00:00+02:00" into the "dd.MM." i.e "07.09."
Thanks in advance!

here is a sample
edited the code:
public static void main(String[] args) throws ParseException {
String input = "2011-09-07T00:00:00+02:00";
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputDf = new SimpleDateFormat("dd.MM");
Date date = inputDf.parse(input.substring(0,9));
System.out.println(date);
System.out.println(outputDf.format(date));
}

Basically -
Create a date format object from the above string
Parse into a date object, and reformat however you prefer.
For example (I haven't tested this):
/*
* REFERENCE:
* http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/
*/
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current time.
DateFormat dfm = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d = dfm.parse("2011-09-07 00:00:00");
// See what toString() returns
System.out.println(" 1. " + d.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(d));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(d));
System.out.println(" 4. " +
DateFormat.getDateTimeInstance().format(d));
// Next, try the short, medium and long variants of the
// default time format
System.out.println(" 5. " +
DateFormat.getTimeInstance(DateFormat.SHORT).format(d));
System.out.println(" 6. " +
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(d));
System.out.println(" 7. " +
DateFormat.getTimeInstance(DateFormat.LONG).format(d));
// For the default date-time format, the length of both the
// date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT).format(d));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(d));
System.out.println("10. " + DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(d));
}
}

Your code needs a little correction on the following line
Date date = inputDf.parse(input.substring(0,9));
In place of (0,9) you need to enter (0,10) and you will be getting the desired output.

tl;dr
OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" ).format( DateTimeFormatter.ofPattern( "dd.MM" )
java.time
The Question and other Answers use old legacy classes that have proven to be troublesome and confusing. They have been supplanted by the java.time classes.
Your input string is in standard ISO 8601 format. These formats are used by default in java.time classes. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" );
You can generate a String in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
String output = odt.format( f );
MonthDay
You want month and day-of-month. There is actually a class for that, MonthDay.
MonthDay md = MonthDay.from( odt );
You can generate a String in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
String output = md.format( f );

Related

How to Convert a 2021-09-29T17:04:31.0000 +05:30 to 2021-09-29 17:04:31.0000000 Asia/Calcutta In Java?

How to Convert a 2021-09-29T17:04:31.0000 +05:30 to 2021-09-29 17:04:31.0000000 Asia/Calcutta In Java?
and additional question is here-
I tried many ways to get the timezone(Asia/Calcutta) from offset(+05:30) but unable to get.
Can someone please help?
Since you cannot derive a zone from an offset (reliably), you may want to use a workaround / different approach.
Here's an example that parses the input String to an OffsetDateTime using a suitable DateTimeFormatter and then creates the desired ZoneId which it applies to the OffsetDateTime in order to create a ZonedDateTime.
public static void main(String[] args) {
// your example input
String offsetTime = "2021-09-29T17:04:31.0000 +05:30";
// define a formatter that parses a String of this format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSS xxx");
// then parse it to an object that knows date, time and offset
OffsetDateTime odt = OffsetDateTime.parse(offsetTime, dtf);
// print the result
System.out.println(odt);
// now define the desired zone
ZoneId asiaCalcutta = ZoneId.of("Asia/Calcutta");
// and use the offset-aware object to apply the zone
ZonedDateTime zdt = odt.atZoneSameInstant(asiaCalcutta);
// print it
System.out.println(zdt);
}
This outputs
2021-09-29T17:04:31+05:30
2021-09-29T17:04:31+05:30[Asia/Calcutta]
Please note: This will only keep the same offset if the offset and the zone actually match. I don't know your concrete requirements, so only you can know if this approach is appropriate in your situation or not.
If you want to find out time zones that currently use a specific offset and then make your code decide which is the correct one, you may want to have a look at this question and its answers.
I tried to write this code to cover three possibilities String parameter , or LocalDateTime parameter and ZonedDateTime Parameter :
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class SpecialFormater {
// parameter : ZonedDateTime
public static String specialFormaterZonedDateTime(ZonedDateTime zdt) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
ZoneId zid = zdt.getZone();
System.out.println("Your initial format =" + zdt);
String result = "Your expected format =" + zdt.format(formatter) + " " + zid;
return result;
}
// parameter : LocalDateTime
public static String specialFormaterLocalDateTime(LocalDateTime dt) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
ZoneId zid = ZoneId.of("Asia/Calcutta");
System.out.println("Your initial format =" + dt);
ZonedDateTime zdt = ZonedDateTime.of(dt, zid);
System.out.println("Your zoned dateTime default format =" + zdt);
String result = "Your expected format =" + dt.format(formatter) + " " + zid;
return result;
}
// Parameter : String
public static String specialFormaterString(String localDateTime) {
System.out.println("String before formatting =" + localDateTime);
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSS xxx";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime dt = LocalDateTime.parse(localDateTime, formatter);
ZoneId zid = ZoneId.of("Asia/Calcutta");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
String result = "String after formatting =" + dt.format(formatter2) + " " + zid;
return result;
}
public static void main(String[] args) {
System.out.println("specialFormaterLocalDateTime");
System.out.println(specialFormaterLocalDateTime(LocalDateTime.now()));
System.out.println("***********");
System.out.println();
System.out.println("specialFormaterString");
System.out.println(specialFormaterString("2021-09-29T17:04:31.0000 +05:30"));
System.out.println("**********");
System.out.println();
System.out.println("specialFormaterZonedDateTime");
System.out.println(specialFormaterZonedDateTime(ZonedDateTime.now()));
}
}
Output :
specialFormaterLocalDateTime
Your initial format =2021-10-06T12:35:45.029
Your zoned dateTime default format =2021-10-06T12:35:45.029+05:30[Asia/Calcutta]
Your expected format =2021-10-06 12:35:45.0290000 Asia/Calcutta
***********
specialFormaterString
String before formatting =2021-09-29T17:04:31.0000 +05:30
String after formatting =2021-09-29 17:04:31.0000000 Asia/Calcutta
**********
specialFormaterZonedDateTime
Your initial format =2021-10-06T12:35:45.064+02:00[Europe/Paris]
Your expected format =2021-10-06 12:35:45.0640000 Europe/Paris
How to get just some time zone that matches the offset using java.time
I tend to understand from your comment under Arvind Kumar Avinash’ answer that you have solved it by simply taking the first time zone that has the correct offset (or what you thought was the correct offset). Of course java.time, the modern Java date and time API, can do that. I wanted to show you a way.
String input = "2021-09-29T17:04:31.0000 +05:30";
// Remove space and parse
OffsetDateTime dateTime = OffsetDateTime.parse(input.replace(" ", ""));
ZoneOffset offset = dateTime.getOffset();
// Find and convert to a zone that matches the offset (there will usually be many)
ZonedDateTime zonedDateTime = ZoneId.getAvailableZoneIds()
.stream()
.map(ZoneId::of)
.map(dateTime::atZoneSameInstant)
.filter(zdt -> zdt.getOffset().equals(offset))
.findFirst()
// If all else fails, use the offset as time zone
.orElse(dateTime.atZoneSameInstant(offset));
// Convert to 2021-09-29 17:04:31.0000000 Asia/Calcutta format
String result = zonedDateTime.format(FORMATTER);
System.out.println(result);
I have used this formatter for formatting the output:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS VV", Locale.ROOT);
And the output is (on my Java 11):
2021-09-29 17:04:31.000000 Asia/Kolkata
Asia/Kolkata is the present-day name for the time zone formerly known as Asia/Calcutta. Is that close enough?
In my code I have taken the case into account where no suitable time zone exists. Let’s see this with an offset that I don’t think is used in any real time zone:
String input = "2021-10-06T18:54:31.0000 +00:30";
2021-10-06 18:54:31.000000 +00:30
If you didn’t want this, you will at least need to change the line with the call to orElse().

Java - How to get the correct date format with LocalDate

I've been having trouble correctly formatting the date as dd-MM-YYYY.
When I arrange the String dateString in the order of year-month-day, or year-day-month, it allows the date to be formatted.
It seems to only work when the yearParsed String as at the begginning of dateString.
Attempting to use DateTimeFormatter.ofPattern("dd-MM-YYYY") didn't seem to affect the date so it looks like I was not using it correctly.
Could you please let me know what I am doing wrong?
The user inputs a day, month and year one at a time, and I am looking to output the date as: 01-12-2000. The if/else are there to add a '0' in front, if the date or month input is a single digit.
Any help would be greatly appreciated.
Thank you!
String yearParsed = String.valueOf(year);
String monthParsed;
String dayParsed;
if (dayString.length() == 1) {
dayParsed = "0" + String.valueOf(day);
}
else {
dayParsed = String.valueOf(day);
}
if (monthString.length() == 1) {
monthParsed = "0" + String.valueOf(month);
}
else {
monthParsed = String.valueOf(month);
}
String dateString = yearParsed + "-" + monthParsed + "-" + dayParsed;
//String dateString = dayParsed + "-" + monthParsed + "-" + yearParsed;
System.out.println("dateString " + dateString);
LocalDate formattedDate = null;
DateTimeFormatter dateTimeFormatter;
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-YYYY");
formattedDate = formattedDate.parse(String.format(dateString, dateTimeFormatter));
System.out.println("Formatted Date = " + formattedDate);
Regarding your variable LocalDate formattedDate, you're misunderstanding the concept of formatted date.
A formatted date is a String, because you can control it's format.
When the object is a LocalDate instance, it contains value to determine a position in the time, when you just print it it has its default formatting, it you want one specific formatting you need a String representation of your date
String year = "2021", dayString = "1", monthString = "3";
LocalDate date = LocalDate.of(
Integer.parseInt(year),
Integer.parseInt(monthString),
Integer.parseInt(dayString)
);
System.out.println(date); // 2021-03-01
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = date.format(dtf);
System.out.println("Formatted Date = " + formattedDate); // Formatted Date = 01-03-2021
You have used Y (week-based-year) instead of y (year-of-era). Learn the difference from the documentation and from answers to this question.
Simply create a LocalDate with the year, month and day and format it to a String using a DateTimeFormatter.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int day = 12, month = 6, year = 2021;
LocalDate date = LocalDate.of(year, month, day);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ENGLISH);
String formatted = dtf.format(date);
System.out.println(formatted);
}
}
Output:
2021-06-12
ONLINE DEMO
Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
Note
A LocalDate is supposed to represent date units (year, month, day), and not a specific format. The default format used by LocalDate#toString is based on ISO 8601 standard. For a specific format, you need to format it into a String as shown above. It is like representing double d = 5.0 as the 5.000 which is done by formatting d into a String of this format.
public class Main {
public static void main(String[] args) {
double d = 5.0;
NumberFormat formatter = new DecimalFormat("#0.000");
String formatted = formatter.format(d);
System.out.println(formatted);
}
}
Output:
5.000

Convert mediumDate() to other format (with Locale) on Joda-Time

I've a problem to convert a date in other format in java (I'm using Joda-Time). In fact, I've a formatted local date as is:
24/giu/14 (Italian format date...but other local formats are possible)
I would like to see this in output (using Locale format date):
24/06/2014
I tried to build a sample code, but doesn't works...what am I doing wrong?
public String DateConvertFromMediumFormatToSlash (String date)
{
DateTimeFormatter dtf = DateTimeFormat.mediumDate().withLocale(Locale.getDefault());
LocalDate dt = dtf.parseLocalDate(date);
return dt.toString(); // output: 2014-06-24
}
Your question is confusing with regards to what you have as input and what you want as output.
Italy Uses Hyphens, Not Slashes
But one problem seems to be the slashes. Joda-Time expects hyphens not slashes. Here is some example code using Joda-Time 2.3 showing you what a LocalDate looks like as a String using the medium format for Locale of Italy.
LocalDate localDate = new LocalDate( 2014, 6, 24 );
System.out.println( "localDate: " + localDate );
DateTimeFormatter formatter = DateTimeFormat.mediumDate().withLocale( Locale.ITALY );
System.out.println( "output: " + formatter.print( localDate ) );
When run…
localDate: 2014-06-24
output: 24-giu-2014
Define A Formatter For Slashes
So if you want to parse/generate a string with slashes instead of the hyphens expected for Locale of Italy, you must explicitly define such a formatter.
String input = "24/giu/14";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "dd/MMM/yy").withLocale( Locale.ITALY );
LocalDate localDate = formatterInput.parseLocalDate( input );
System.out.println( "localDate: " + localDate );
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "dd/MM/yy").withLocale( Locale.ITALY ); // Locale not needed here, but it's a good habit to specify.
String output = formatterOutput.print( localDate );
System.out.println( "Output: " + output );
When run…
localDate: 2014-06-24
Output: 24/06/14
By the way, using two digits for the year is asking for trouble IMHO.

Convert miliseconds to date and time and format by locale

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));

Convert java.util.Date to String

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());

Categories