Related
This question already has answers here:
How to set time zone of a java.util.Date?
(12 answers)
Closed 7 months ago.
I want to change the time zone of given date. I use this code, but i dont have the good result.
My input is "2020-06-16 14:00:00" time in Europe/Paris, and I wnat to change it to UTC, that means I want to get "2020-06-16 12:00:00", but I get initial result "2020-06-16 14:00:00".
try {
// Calendar calParis = Calendar.getInstance();
String heure = "1400";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-16");
String hour = heure.substring(0, heure.length() - 2);
String minute = heure.substring(heure.length() - 2);
Calendar cal = Calendar.getInstance();
String datenew = "2020-06-16" + " " + hour + ":" + minute + ":00";
SimpleDateFormat sdfDatenew = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date thisDate = sdfDatenew.parse(datenew);
cal.setTime(thisDate);
cal.setTimeZone(TimeZone.getTimeZone("Europe/UTC"));
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
String dateISO = null;
dateISO = sdfDate.format(cal.getTime());
System.out.println("Time in ISO: " + dateISO);
} catch (Exception ex) {
}
Here you go:
This way you can get your dates and time in Java-7 format.
public static void main(String[] args) throws ParseException {
String heure = "1400";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-16");
String hour = heure.substring(0, heure.length() - 2);
String minute = heure.substring(heure.length() - 2);
String datenew = "2020-06-16" + " " + hour + ":" + minute + ":00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Calendar calendar = Calendar.getInstance();
Date thisDate = sdf.parse(datenew);
calendar.setTime(thisDate);
sdf.setTimeZone(TimeZone.getTimeZone("PDT"));
System.out.println(sdf.format(calendar.getTime())); // prints 2020-06-16 12:00:00
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(calendar.getTime())); // prints 2020-06-16 14:00:00
}
tl;dr
LocalDateTime
.parse(
"2020-06-16 14:00:00"
.replace( " " , "T" )
)
.atZone(
ZoneId.of( "Europe/Paris" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
.format(
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )
)
See this code run live at IdeOne.com.
2020-06-16 12:00:00
java.time
The modern solution uses java.time classes.
Your input string lacks a time zone or offset. So parse as a LocalDateTime object.
LocalDateTime ldt = LocalDateTime.parse( "2020-06-16 14:00:00".replace( " " , "T" ) ) ;
You say with certainty that this string represents a moment as seen in Paris France time zone.
ZoneId zParis = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = ldt.atZone( zParis ) ;
Adjust from there to your target time zone. You happen to want UTC, so just extract an Instant.
Instant instant = zdt.toInstant() ;
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.
The answer by Basil Bourque is correct but I would not use String replacement when DateTimeFormatter is capable enough to address this and much more.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String input = "2020-06-16 14:00:00";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(input, dtfInput);
ZonedDateTime zdtParis = ldt.atZone(ZoneId.of("Europe/Paris"));
ZonedDateTime zdtUtc = zdtParis.withZoneSameInstant(ZoneId.of("Etc/UTC"));
// Default format
System.out.println(zdtUtc);
// Custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
String output = dtfOutput.format(zdtUtc);
System.out.println(output);
}
}
Output:
2020-06-16T12:00Z[Etc/UTC]
2020-06-16 12:00:00
ONLINE DEMO
All in a single statement:
System.out.println(
LocalDateTime
.parse("2020-06-16 14:00:00", DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH))
.atZone(ZoneId.of("Europe/Paris"))
.withZoneSameInstant(ZoneId.of("Etc/UTC"))
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH))
);
ONLINE DEMO
Some important notes:
You can use a single pattern, uuuu-MM-dd HH:mm:ss for both of your input and output strings but I prefer using u-M-d H:m:s for parsing because uuuu-MM-dd HH:mm:ss will fail if you have a year in two digits, a month in single digit, a day-of-month in single digit etc. For parsing, a single u can cater to both, two-digit and four-digit year representation. Similarly, a single M can cater to both one-digit and two-digit month. Similar is the case with other symbols.
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.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I'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));
I am trying to use the Android SimpleDateFormat like this:
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(_Date);
return fmt.format(date);
}
catch(ParseException pe) {
return "Date";
}
The result is good and I have: 2010-09-29
But if I change the SimpleDateFormat to
SimpleDateFormat("dd-MM-yyyy");
the problem is that I will got 03-03-0035 !!!!
Why and how to get the format like dd-MM-yyyy?
I assume you would like to reverse the date format?
SimpleDateFormat can be used for parsing and formatting.
You just need two formats, one that parses the string and the other that returns the desired print out:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Since Java 8:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
TemporalAccessor date = fmt.parse(dateString);
Instant time = Instant.from(date);
DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
return fmtOut.format(time);
Below is all date formats available, read more doc here.
Symbol Meaning Kind Example
D day in year Number 189
E day of week Text E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month Number 2 (2nd Wed in July)
G era designator Text AD
H hour in day (0-23) Number 0
K hour in am/pm (0-11) Number 0
L stand-alone month Text L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year Text M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds Number 978
W week in month Number 2
Z time zone (RFC 822) Time Zone Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker Text PM
c stand-alone day of week Text c/cc/ccc:Tue, cccc:Tuesday, ccccc:T
d day in month Number 10
h hour in am/pm (1-12) Number 12
k hour in day (1-24) Number 24
m minute in hour Number 30
s second in minute Number 55
w week in year Number 27
G era designator Text AD
y year Number yy:10 y/yyy/yyyy:2010
z time zone Time Zone z/zz/zzz:PST zzzz:Pacific Standard
I think this Link might helps you
OR
Date date = Calendar.getInstance().getTime();
//
// Display a date in day, month, year format
//
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmt2 = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(_Date);
return fmt2.format(date);
}
catch(ParseException pe) {
return "Date";
}
try this.
Using the date-time API of java.util and their formatting API, SimpleDateFormat I have come across surprises several times but this is the biggest one! 😮😮😮
Given below is the illustration of what you have described in your question:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
}
Output:
2010-09-29
03-03-0035
Surprisingly, SimpleDateFormat silently performed the parsing and formatting without raising an alarm. Anyone reading this will not have a second thought to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
Since the pattern used in both the functions are wrong as per the input string, the parser should raise the alarm and the parsing/formatting types of the modern date-time API do it responsibly.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
}
Output:
Date
Date
Moral of the story
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. Stop using them completely and switch to the modern date-time API. Learn about the modern date-time API at Trail: Date Time.
Stick to the format in your input date-time string while parsing it. If you want the output in a different format, use a differnt instance of the parser/formatter class.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String strDateTime = "2010-09-29 08:45:22";
DateTimeFormatter dtfForParsing = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtfForParsing);
System.out.println(ldt);// The default format as returned by LocalDateTime#toString
// Some custom formats for output
System.out.println("########In custom formats########");
DateTimeFormatter dtfForFormatting1 = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss");
DateTimeFormatter dtfForFormatting2 = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter dtfForFormatting3 = DateTimeFormatter.ofPattern("'Day: 'EEEE, 'Date: 'MMMM dd uuuu");
System.out.println(dtfForFormatting1.format(ldt));
System.out.println(dtfForFormatting2.format(ldt));
System.out.println(dtfForFormatting3.format(ldt));
System.out.println("################################");
}
}
Output:
2010-09-29T08:45:22
########In custom formats########
29-09-2010 08:45:22
29-09-2010
Day: Wednesday, Date: September 29 2010
################################
This worked for me...
#SuppressLint("SimpleDateFormat")
private void setTheDate() {
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("MM'/'dd'/'y hh:mm");
curDate = formatter.format(curDateTime);
mDateText.setText("" + curDate);
}
java.time and desugaring
I recommend that you use java.time, the modern Java date and time API, for your date work. First define a formatter for your string:
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
Then do:
String dateString = "2010-09-29 08:45:22";
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
String newString = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(newString);
Output is:
2010-09-29
I find it a good practice to parse the entire string even though we currently have no use for the time of day. That may come some other day. java.time furnishes a predefined formatter for your first output format, DateTimeFormatter.ISO_LOCAL_DATE. If you want the opposite order of day, month and year, we will need to write our own formatter for that:
private static DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd-MM-uuuu");
Then we can obtain that too:
String dmyReversed = dateTime.format(dateFormatter);
System.out.println(dmyReversed);
29-09-2010
What went wrong in your code?
the problem is that I will got 03-03-0035 !!!!
This is how confusing a SimpleDateFormat with standard settings is: With format pattern dd-MM-yyyy it parses 2010-09-29 as the 2010th day of month 9 of year 29. Year 29 AD that is. And it doesn’t disturb it that there aren’t 2010 days in September. It just keeps counting days through the following months and years and ends up five and a half years later, on 3 March year 35.
Which is just a little bit of the reason why I say: don’t use that class.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Wikipedia article: ISO 8601
Here is an easy example of SimpleDateFormat tried in Android Studio 3 and Java 9:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String strDate = sdf.format(strDate);
Note:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); shows
some deprecation warning in Android Studio 3 Lint. So, add a second
parameter Locale.US to specify the Localization in date formatting.
It took a lot of efforts. I did a lot of hit and trial and finally I got the solution. I had used ""MMM"" for showing month as: JAN
If you looking for date, month and year separately
or how to use letters from answer of heloisasim
SimpleDateFormat day = new SimpleDateFormat("d");
SimpleDateFormat month = new SimpleDateFormat("M");
SimpleDateFormat year = new SimpleDateFormat("y");
Date d = new Date();
String dayS = day.format(d);
String monthS = month.format(d);
String yearS = year.format(d);
public String formatDate(String dateString) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = fmt.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
}
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
The code below gives me the current time. But it does not tell anything about milliseconds.
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
I have a date in the format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).
But I want to retrieve the current time in the format YYYY-MM-DD HH:MM:SS.MS (2009-09-22 16:47:08.128, where 128 are the milliseconds).
SimpleTextFormat will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
A Java one liner
public String getCurrentTimeStamp() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
in JDK8 style
public String getCurrentLocalDateTimeStamp() {
return LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}
You only have to add the millisecond field in your date format string:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The API doc of SimpleDateFormat describes the format string in detail.
try this:-
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
tl;dr
Instant.now()
.toString()
2016-05-06T23:24:25.694Z
ZonedDateTime
.now
(
ZoneId.of( "America/Montreal" )
)
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19:24:25.694
java.time
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.
An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T in the middle with a space, and the Z with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
Joda-Time
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
The easiest way was to (prior to Java 8) use,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.
So in Java 8 something like below will do the trick (to format the current date/time),
LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
And one thing to note is it was developed with the help of the popular third party library joda-time,
The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.
But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project
Anyway having said that,
If you have a Calendar instance you can use below to convert it to the new java.time,
Calendar calendar = Calendar.getInstance();
long longValue = calendar.getTimeInMillis();
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(date.toString()); // 2018-03-06T15:56:53.634
System.out.println(formattedString); // 2018-03-06 15:56:53.634
If you had a Date object,
Date date = new Date();
long longValue2 = date.getTime();
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
System.out.println(formattedString); // 2018-03-06 15:59:30.278
If you just had the epoch milliseconds,
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.
I have a simple example here to display date and time with Millisecond......
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass{
public static void main(String[]args){
LocalDateTime myObj = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String forDate = myObj.format(myFormat);
System.out.println("The Date and Time are: " + forDate);
}
}
To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.
import java.text.SimpleDateFormat;
import java.util.Date;
public class test {
public static void main(String argv[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);
}
}
Use this to get your current time in specified format :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(dateFormat.format(System.currentTimeMillis())); }
java.time
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2009. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
LocalDateTime.now(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))
Some important points about this solution:
Replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
If the current date-time is required in the system's default timezone (ZoneId), you do not need to use LocalDateTime#now(ZoneId zone); instead, you can use LocalDateTime#now().
You can use y instead of u here but I prefer u to y.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
// Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
// ZoneId.of("America/New_York")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
String formattedDateTimeStr = ldt.format(formatter);
System.out.println(formattedDateTimeStr);
}
}
Output from a sample run in my system's timezone, Europe/London:
2023-01-02 09:53:14.353
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
I don't see a reference to this:
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
above format is also useful.
http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm
Ans:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);
java.text (prior to java 8)
public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
};
};
...
dateFormat.get().format(new Date());
java.time
public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
...
dateTimeFormatter.format(LocalDateTime.now());
The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion
You can simply get it in the format you want.
String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));