Parse String to Date with Different Format in Java - java

I want to convert String to Date in different formats.
For example,
I am getting from user,
String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format
I want to convert this fromDate as a Date object of "yyyy-MM-dd" format
How can I do this?

Take a look at SimpleDateFormat. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}

tl;dr
LocalDate.parse(
"19/05/2009" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
Details
The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f =
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );
Dump to console.
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
See in action in IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Use the SimpleDateFormat class:
private Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
Usage:
Date date = parseDate("19/05/2009", "dd/MM/yyyy");
For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.
private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = hashFormatters.get(format);
if (formatter == null)
{
formatter = new SimpleDateFormat(format);
hashFormatters.put(format, formatter);
}
return formatter.parse(date);
}

Convert a string date to java.sql.Date
String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

Simple way to format a date and convert into string
Date date= new Date();
String dateStr=String.format("%td/%tm/%tY", date,date,date);
System.out.println("Date with format of dd/mm/dd: "+dateStr);
output:Date with format of dd/mm/dd: 21/10/2015

Suppose that you have a string like this :
String mDate="2019-09-17T10:56:07.827088"
Now we want to change this String format separate date and time in Java and Kotlin.
JAVA:
we have a method for extract date :
public String getDate() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mDate);
dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return is this : 09/17/2019
And we have method for extract time :
public String getTime() {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
Date date = dateFormat.parse(mCreatedAt);
dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
return dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Return is this : 10:56 AM
KOTLIN:
we have a function for extract date :
fun getDate(): String? {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val date = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return dateFormat.format(date!!)
}
Return is this : 09/17/2019
And we have method for extract time :
fun getTime(): String {
var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
val time = dateFormat.parse(mDate!!)
dateFormat = SimpleDateFormat("h:mm a", Locale.US)
return dateFormat.format(time!!)
}
Return is this : 10:56 AM

A Date object has no format, it is a representation. The date can be presented by a String with the format you like.
E.g. "yyyy-MM-dd", "yy-MMM-dd", "dd-MMM-yy" and etc.
To acheive this you can get the use of the SimpleDateFormat
Try this,
String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
System.out.println(dateMyFormat); // outputs : 2009-05-19
} catch (ParseException e) {
e.printStackTrace();
}
This outputs : 2009-05-19

There are multiple ways to do it, but a very practical one is the use String.format which you can use with java.util.Date or java.util.Calendar or event java.time.LocalDate.
String.format is backed by java.util.Formatter.
I like the omnivore take on it.
class Playground {
public static void main(String[ ] args) {
String formatString = "Created on %1$td/%1$tm/%1$tY%n";
System.out.println(String.format(formatString, new java.util.Date()));
System.out.println(String.format(formatString, java.util.Calendar.getInstance()));
System.out.println(String.format(formatString, java.time.LocalDate.now()));
}
}
The output will be in all cases:
Created on 04/12/2022
Created on 04/12/2022
Created on 04/12/2022

Related

How to get the format of a date passed as string in Java [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
I Am passing date as string
Input: "8 Aug 2016"
I want output as format of above date i.e.
Output: DD MMM YYYY
Can anyone help here?
You can try using a fixed number of predefined date formats and then use SimpleDateFormat to parse the date to test against. Use the first one that doesn't throw an exception.
Note however that there's no way to do this with complete certainty. There are simply too many alternatives, and they are often ambiguous (consider e.g. MM/dd/yyyy versus dd/MM/yyyy).
tl;dr
LocalDate.parse( "8 Aug 2016" , DateTimeFormatter.ofPattern ( "d MMM uuuu" ).withLocale ( Locale.US ) )
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also 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.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern. Specify the Locale defining the human language of the name of the month. If omitted the JVM’s current default Locale is implicitly applied. That default can vary. Better to specify your desired/expected Locale explicitly.
String input = "8 Aug 2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "d MMM uuuu" );
f = f.withLocale ( Locale.US );
LocalDate ld = LocalDate.parse ( input , f );
String output = ld.format ( f );
Dump to console.
System.out.println ( "input: " + input + " | ld: " + ld + " | output: " + output );
input: 8 Aug 2016 | ld: 2016-08-08 | output: 8 Aug 2016
Of course your parsing code should trap for DateTimeParseException being thrown. Omitted here for brevity.
ISO 8601
I strongly recommend passing around date-time strings in the standard formats of ISO 8601. For a date-only value, that would be YYYY-MM-DD.
String input = "2016-08-08" ;
LocalDate ld = LocalDate.parse( input );
String output = ld.toString(); // "2016-08-08"
public static void main(String[] args) throws ParseException {
String time = "8 Aug 2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
Date date = sdf.parse(time);// this parses your string into a date.
System.out.println(sdf.format(date));//this will format your date in the format you specify.
}
here is a nice tutorial on converting string objects to date. link
new SimpleDateFormat("dd MMM yyyy").format(yourDateObject);
Have a look at java.text.SimpleDateFormat. It allows you to specify formats for both parsing and output formatting.
import java.text.SimpleDateFormat;
public class DateDemo {
public static void main(String[] argv) {
SimpleDateFormat parser = new SimpleDateFormat("d MMM yyyy");
try {
java.util.Date date = parser.parse("8 Aug 2016");
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(formatter.format(date));
} catch (java.text.ParseException e) { // won't happen here
System.err.println("Invalid date");
}
}
}
Instead of fetching the date format, I compared the actual date with date of required format (by converting actual date in that format) as below.
public static boolean isValidFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
return true;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
return false;
}
Here I am passing two parameters to the method isValidFormat() , one is the format of the date I need to validate as String format and String value as value of date and then performing the format check of both dates (one parsed in required format and actual value) and returning the result accordingly.

How to convert date to string and to date again?

Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into String format, but i want to convert it back into Date format. So can anyone advise on this?
This is my code so far
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestring = dateFormat.format(date);
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
Use DateFormat#parse(String):
Date date = dateFormat.parse("2013-10-22");
tl;dr
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
java.time
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
ISO 8601
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
try this function
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}
Convert Date to String using this function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
System.out.println(ex);
}
return dateStr;
}
From Convert Date to String in Java
. And convert string to date again
public Date convertStringToDate(String dateStr, String format) {
Date date = null;
DateFormat df = new SimpleDateFormat(format);
try {
date = df.parse(dateStr);
} catch (Exception ex) {
System.out.println(ex);
}
return date;
}
From Convert String to date in Java

How do I convert the date from one format to another date object in another format without using any deprecated classes?

I'd like to convert a date in date1 format to a date object in date2 format.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 21);
Date date = cal.getTime();
Date date1 = simpleDateFormat.parse(date);
Date date2 = simpleDateFormat.parse(date1);
println date1
println date2
Use SimpleDateFormat#format:
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
Also note that parse takes a String, not a Date object, which is already parsed.
tl;dr
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
Using java.time
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
You have date-only values, so use a date-only class. The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08 and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108.
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter class named BASIC_ISO_DATE.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
ld.toString(): 2017-01-08
output: 20170108
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Since Java 8, we can achieve this as follows:
private static String convertDate(String strDate)
{
//for strdate = 2017 July 25
DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
.toFormatter();
LocalDate parsedDate = LocalDate.parse(strDate, f);
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String newDate = parsedDate.format(f2);
return newDate;
}
The output will be : "07/25/2017"
Try this
This is the simplest way of changing one date format to another
public String changeDateFormatFromAnother(String date){
#SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
#SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
String resultDate = "";
try {
resultDate=outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
Kotlin equivalent of answer answered by João Silva
fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
return targetFormat.format(originalFormat.parse(inputDate))
}
Usage (In Android):
getFormattedDate(
SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
dateOfTreatment
)
Note: Constant values:
// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"
// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date
as argument2, and the result (expected) format as argument 3.
Refer to this link to understand various formats:
Available Date Formats
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
private String formatDate(String date, String inputFormat, String outputFormat) {
String newDate;
DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
inputDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
try {
newDate = outputDateFormat.format((inputDateFormat.parse(date)));
} catch (Exception e) {
newDate = "";
}
return newDate;
}
Hope this will help someone.
public static String getDate(
String date, String currentFormat, String expectedFormat)
throws ParseException {
// Validating if the supplied parameters is null
if (date == null || currentFormat == null || expectedFormat == null ) {
return null;
}
// Create SimpleDateFormat object with source string date format
SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
// Parse the string into Date object
Date dateObj = sourceDateFormat.parse(date);
// Create SimpleDateFormat object with desired date format
SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
// Parse the date into another format
return desiredDateFormat.format(dateObj).toString();
}
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
String fromDateFormat = "dd/MM/yyyy";
String fromdate = 15/03/2018; //Take any date
String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
String dateStringFrom;
Date DF = new Date();
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false); // this is important!
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new
SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println(dateStringFrom);
}
catch(Exception ex)
{
System.out.println("Date error");
}
output:- 15/03/2018
15 Mar 2018
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));

how to convert milliseconds to date format in android?

I have milliseconds.
I need it to be converted to date format of
example:
23/10/2011
How to achieve it?
Just Try this Sample code:-
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test {
/**
* Main Method
*/
public static void main(String[] args) {
System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
}
/**
* Return date in specified format.
* #param milliSeconds Date in milliseconds
* #param dateFormat Date format
* #return String representing date in specified format
*/
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat 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);
return formatter.format(calendar.getTime());
}
}
Convert the millisecond value to Date instance and pass it to the choosen formatter.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(dateInMillis)));
public static String convertDate(String dateInMilliseconds,String dateFormat) {
return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}
Call this function
convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
tl;dr
Instant.ofEpochMilli( myMillisSinceEpoch ) // Convert count-of-milliseconds-since-epoch into a date-time in UTC (`Instant`).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust into the wall-clock time used by the people of a particular region (a time zone). Produces a `ZonedDateTime` object.
.toLocalDate() // Extract the date-only value (a `LocalDate` object) from the `ZonedDateTime` object, without time-of-day and without time zone.
.format( // Generate a string to textually represent the date value.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Specify a formatting pattern. Tip: Consider using `DateTimeFormatter.ofLocalized…` instead to soft-code the formatting pattern.
) // Returns a `String` object.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes used by all the other Answers.
Assuming you have a long number of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z…
Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;
To get a date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
Extract a date-only value.
LocalDate ld = zdt.toLocalDate() ;
Generate a String representing that value using standard ISO 8601 format.
String output = ld.toString() ;
Generate a String in custom format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;
Tip: Consider letting java.time automatically localize for you rather than hard-code a formatting pattern. Use the DateTimeFormatter.ofLocalized… methods.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
try this code might help, modify it suit your needs
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);
DateFormat.getDateInstance().format(dateInMS);
i finally find normal code that works for me
Long longDate = Long.valueOf(date);
Calendar cal = Calendar.getInstance();
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
Date da = new Date();
da = new Date(longDate-(long)offset);
cal.setTime(da);
String time =cal.getTime().toLocaleString();
//this is full string
time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(da);
//this is only time
time = DateFormat.getDateInstance(DateFormat.MEDIUM).format(da);
//this is only date
Short and effective:
DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
Coverting epoch format to SimpleDateFormat in Android (Java / Kotlin)
input: 1613316655000
output: 2021-02-14T15:30:55.726Z
In Java
long milliseconds = 1613316655000L;
Date date = new Date(milliseconds);
String mobileDateTime = Utils.getFormatTimeWithTZ(date);
//method that returns SimpleDateFormat in String
public static String getFormatTimeWithTZ(Date currentTime) {
SimpleDateFormat timeZoneDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
return timeZoneString = timeZoneDate.format(currentTime);
}
In Kotlin
var milliseconds = 1613316655000L
var date = Date(milliseconds)
var mobileDateTime = Utils.getFormatTimeWithTZ(date)
//method that returns SimpleDateFormat in String
fun getFormatTimeWithTZ(currentTime:Date):String {
val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
return timeZoneString = timeZoneDate.format(currentTime)
}
Latest solution in Kotlin:
private fun getDateFromMilliseconds(millis: Long): String {
val dateFormat = "MMMMM yyyy"
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
val calendar = Calendar.getInstance()
calendar.timeInMillis = millis
return formatter.format(calendar.time)
}
We need to add Locale as an argument of SimpleDateFormat or use LocalDate. Locale.getDefault() is a great way to let JVM automatically get the current location timezone.
public class LogicconvertmillistotimeActivity extends Activity {
/** Called when the activity is first created. */
EditText millisedit;
Button millisbutton;
TextView millistextview;
long millislong;
String millisstring;
int millisec=0,sec=0,min=0,hour=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
millisedit=(EditText)findViewById(R.id.editText1);
millisbutton=(Button)findViewById(R.id.button1);
millistextview=(TextView)findViewById(R.id.textView1);
millisbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
millisbutton.setClickable(false);
millisec=0;
sec=0;
min=0;
hour=0;
millisstring=millisedit.getText().toString().trim();
millislong= Long.parseLong(millisstring);
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
if(millislong>1000){
sec=(int) (millislong/1000);
millisec=(int)millislong%1000;
if(sec>=60){
min=sec/60;
sec=sec%60;
}
if(min>=60){
hour=min/60;
min=min%60;
}
}
else
{
millisec=(int)millislong;
}
cal.clear();
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,min);
cal.set(Calendar.SECOND, sec);
cal.set(Calendar.MILLISECOND,millisec);
String DateFormat = formatter.format(cal.getTime());
// DateFormat = "";
millistextview.setText(DateFormat);
}
});
}
}
I've been looking for an efficient way to do this for quite some time and the best I've found is:
DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(millis));
Advantages:
It's localized
Been in Android since API 1
Very simple
Disadvantages:
Limited format options. FYI: SHORT is only a 2 digit year.
You burn a Date object every time. I've looked at source for the other options and this is a fairly minor compared to their overhead.
You can cache the java.text.DateFormat object, but it's not threadsafe. This is OK if you are using it on the UI thread.
This is the easiest way using Kotlin
private const val DATE_FORMAT = "dd/MM/yy hh:mm"
fun millisToDate(millis: Long) : String {
return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
}
public static Date getDateFromString(String date) {
Date dt = null;
if (date != null) {
for (String sdf : supportedDateFormats) {
try {
dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
break;
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
return dt;
}
public static Calendar getCalenderFromDate(Date date){
Calendar cal =Calendar.getInstance();
cal.setTime(date);return cal;
}
public static Calendar getCalenderFromString(String s_date){
Date date = getDateFromString(s_date);
Calendar cal = getCalenderFromDate(date);
return cal;
}
public static long getMiliSecondsFromString(String s_date){
Date date = getDateFromString(s_date);
Calendar cal = getCalenderFromDate(date);
return cal.getTimeInMillis();
}
public static String toDateStr(long milliseconds, String format)
{
Date date = new Date(milliseconds);
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
return formatter.format(date);
}
Use SimpleDateFormat for Android N and above. Use the calendar for earlier versions
for example:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fileName = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
Log.i("fileName before",fileName);
}else{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,1);
String zamanl =""+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND);
fileName= zamanl;
Log.i("fileName after",fileName);
}
Output:
fileName before: 2019-04-12-07:14:47 // use SimpleDateFormat
fileName after: 2019-4-12-7:13:12 // use Calender
fun convertLongToTimeWithLocale(){
val dateAsMilliSecond: Long = 1602709200000
val date = Date(dateAsMilliSecond)
val language = "en"
val formattedDateAsDigitMonth = SimpleDateFormat("dd/MM/yyyy", Locale(language))
val formattedDateAsShortMonth = SimpleDateFormat("dd MMM yyyy", Locale(language))
val formattedDateAsLongMonth = SimpleDateFormat("dd MMMM yyyy", Locale(language))
Log.d("month as digit", formattedDateAsDigitMonth.format(date))
Log.d("month as short", formattedDateAsShortMonth.format(date))
Log.d("month as long", formattedDateAsLongMonth.format(date))
}
output:
month as digit: 15/10/2020
month as short: 15 Oct 2020
month as long : 15 October 2020
You can change the value defined as 'language' due to your require. Here is the all language codes:
Java language codes

How can I change the date format in Java? [duplicate]

This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 3 years ago.
I need to change the date format using Java from
dd/MM/yyyy to yyyy/MM/dd
How to convert from one date format to another using SimpleDateFormat:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());
This should do the trick
tl;dr
LocalDate.parse(
"23/01/2017" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )
).format(
DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)
2017/01/23
Avoid legacy date-time classes
The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
Using java.time
Parse the input string as a date-time object, then generate a new String object in the desired format.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
Define another formatter for the output.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );
2017/01/23
By the way, consider using standard ISO 8601 formats for strings representing date-time values.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.
For fun, here is his code adapted for using the Joda-Time library.
// © 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.*;
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
When run…
localDate: 2010-08-12
newDateString: 2010/08/12
Use SimpleDateFormat
String DATE_FORMAT = "yyyy/MM/dd";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Formated Date " + sdf.format(date));
Complete Example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaSimpleDateFormatExample {
public static void main(String args[]) {
// Create Date object.
Date date = new Date();
// Specify the desired date format
String DATE_FORMAT = "yyyy/MM/dd";
// Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
/*
* Use format method of SimpleDateFormat class to format the date.
*/
System.out.println("Today is " + sdf.format(date));
}
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("yyyy/MM/dd")
String myDateString = sdf.format(myDate);
Now myDateString = 2013/12/28
This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:
final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);
1 well, not that new anymore, Java 9 should be released soon.
Or you could go the regex route:
String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);
It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.
many ways to change date format
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();
final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);
final String nowString = format.format(now);
final Instant instant = now.toInstant();
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
dateTimeFormatPattern).withZone(ZoneId.systemDefault());
final String formattedInstance = formatter.format(instant);
/* Java 8 needed*/
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
To Change the format of Date you have Require both format look below.
String stringdate1 = "28/04/2010";
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = format1.parse()
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
String stringdate2 = format2.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
here stringdate2 have date format of yyyy/MM/dd. and it contain 2010/04/28.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));

Categories

Resources