I have a string value which is equal to "202004". how can I convert it to "April, 2020" in Java?
I would use java.time for a task like this.
You can define two java.time.format.DateTimeFormatter instances (one for parsing the input string to java.time.YearMonth and another for formatting the obtained YearMonth to a string of the desired format).
Define a method like this one:
public static String convert(String monthInSomeYear, Locale locale) {
// create something that is able to parse such input
DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("uuuuMM");
// then use that formatter in order to create an object of year and month
YearMonth yearMonth = YearMonth.parse(monthInSomeYear, inputParser);
/*
* the output format is different, so create another formatter
* with a different pattern. Please note that you need a Locale
* in order to define the language used for month names in the output.
*/
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(
"MMMM, uuuu",
Locale.ENGLISH
);
// then return the desired format
return yearMonth.format(outputFormatter);
}
then use it, e.g. in a main method:
public static void main(String[] args) {
// your example input
String monthInAYear = "202004";
// use the method
String sameMonthInAYear = convert(monthInAYear, Locale.ENGLISH);
// and print the result
System.out.println(sameMonthInAYear);
}
The output will be this:
April, 2020
Use below one line code to format year month
int yearMonth = Integer.parseInt("202004");
String yearMonthStr = new DateFormatSymbols().getMonths()[(yearMonth % 10)-1] + ", "+yearMonth/100;
System.out.println(yearMonthStr);
Use DateFormatSymbols() class to implement the new date format from the string
String text="202011";
int num=0;
//Checking the last second character of the text for jan to sept month
if(text.charAt(text.length()-2)==0){
num=Integer.parseInt(""+text.charAt(text.length()-1))-1;
}
else {
num=Integer.parseInt(""+text.substring(text.length()-2))-1;
}
//Checking correct month value
if(num>=0&&num<=11){
String month = "";
DateFormatSymbols date_ = new DateFormatSymbols();
String[] month_name = date_.getMonths();
month = month_name[num];
System.out.println(month+","+text.substring(0,4));
}
else{
System.out.println("Wrong month value");
}
SimpleDateFormat oldFormat = new SimpleDateFormat("yyyyMM");
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM, yyyy");
Date date = null;
try {
date = oldFormat.parse("202004");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = newFormat.format(date);
SimpleDateFormat documentation
Let try my code snippet:
SimpleDateFormat inSdf = new SimpleDateFormat("yyyyMM");
Date date = inSdf.parse("202112");
SimpleDateFormat outSdf = new SimpleDateFormat("MMMM, yyyy");
String sDate = outSdf.format(date);
System.out.println(sDate);
Result:
December, 2021
I am trying to format a DateTime string that is received from the server. I have used the below formats and none is working - AppConstants.API_DATE_TIME_FORMAT =
- `"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"`
- `"yyyy-MM-dd'T'HH:mm:ss.SSSZ'Z'"`
- `"yyyy-MM-dd'T'HH:mm:ss.SSSZ"`
- `"yyyy-MM-dd'T'HH:mm:ss.SSSXX'Z'"`
- `"yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'"`
and -
fun getFormattedDate(apiFormatDateTime: String): String {
return try{
val parser = SimpleDateFormat(AppConstants.API_DATE_TIME_FORMAT, Locale.getDefault())
val formatter = SimpleDateFormat(AppConstants.UI_DATE_FORMAT, Locale.getDefault())
val date = parser.parse(apiFormatDateTime)!!
formatter.format(date)
}catch (ex : Exception){
apiFormatDateTime
}
}
This works
String d="2020-05-08T11:01:48.3300000Z";
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse(d);
String formattedDate = targetFormat.format(date);
System.out.println("date==>"+formattedDate);
Output::
date==>20200508
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. In Java (because this is what I can write):
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter uiDateFormatter = DateTimeFormatter.ofPattern("M/d/uuuu");
String isoF8601ormatDateTime = "2020-05-08T11:01:48.3300000Z";
Instant time = Instant.parse(isoF8601ormatDateTime);
String uiString = time.atZone(zone)
.format(uiDateFormatter);
System.out.println(uiString);
Output is:
5/8/2020
Points to note:
The format from your API is ISO 8601. The classes of java.time parse the most common ISO 8601 variants as their default, that is, we need not specify any formatter.
My code also converts the date to the user’s time zone before formatting. Most users will expect this. Please put your user’s time zone where I put Asia/Kolkata.
Bonus info: to format the time, in the user’s time zone too:
DateTimeFormatter uiTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String uiTimeString = time.atZone(zone).format(uiTimeFormatter);
System.out.println(uiTimeString);
04:31:48 PM
What went wrong in your attemtps?
There exists no way that SimpleDateFormat can parse 7 decimals on the seconds correctly. It only supports milliseconds, exactly three decimals. SimpleDateFormat takes 3300000 to be milliseconds, that is 3300 seconds or nearly an hour, which it adds to the time parsed.
Z in your incoming string is a UTC offset (of zero) and needs to be parsed as such, or you will get an incorrect result.
Z without quotes will parse an offset like +0000, but not Z. XX will parse Z, but that attempt failed because you additionally required (one more) Z after the Z.
You did not convert to the user’s time zone before formatting.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
You could try using LocalDateTime and DateTimeFormatter
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
credit to :https://stackoverflow.com/a/22463063/9297896
You can try it like below
try {
XMLGregorianCalendar dt = DatatypeFactory.newInstance().newXMLGregorianCalendar("2020-05-13T12:12:12.123456Z");
String dateValue = new SimpleDateFormat("MM/dd/yyyy").format(dt.toGregorianCalendar().getTime());
System.out.println("datevalue="+dateValue);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
output: datevalue=05/13/2020
Here is how I did it for getting date and time from UTC format -
const val API_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"
const val UI_DATE_FORMAT = "MM/dd/yyyy"
const val UI_TIME_FORMAT = "hh:mm:ss a"
/**
* Function for getting date from api datetime string
* #return formatted time
*/
fun getFormattedDate(apiFormatDateTime: String): String {
return try{
val parser = SimpleDateFormat(AppConstants.API_DATE_TIME_FORMAT, Locale.getDefault())
parser.timeZone = TimeZone.getTimeZone("UTC")
val formatter = SimpleDateFormat(AppConstants.UI_DATE_FORMAT, Locale.getDefault())
val date = parser.parse(apiFormatDateTime)!!
formatter.timeZone = TimeZone.getDefault()
formatter.format(date)
}catch (ex : Exception){
apiFormatDateTime
}
}
/**
* Function for getting time from api datetime string
* #return formatted time
*/
fun getFormattedTime(apiFormatDateTime: String): String {
return try{
val parser = SimpleDateFormat(AppConstants.API_DATE_TIME_FORMAT, Locale.getDefault())
parser.timeZone = TimeZone.getTimeZone("UTC")
val formatter = SimpleDateFormat(AppConstants.UI_TIME_FORMAT, Locale.getDefault())
formatter.timeZone = TimeZone.getDefault()
formatter.format(parser.parse(apiFormatDateTime)!!)
}catch (ex : Exception){
apiFormatDateTime
}
}
I Have a bean , in that I have one property of date type.
private Date insurance_date;
public Date getInsurance_date() {
return insurance_date;
}
public void setInsurance_date(Date insurance_date) {
this.insurance_date = insurance_date;
}
But get method gives us a date with time so I wrote a formated method as,
public String getFormatedDoI() {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String stirngDate = null ;
if(insurance_date != null)
stirngDate = df.format((insurance_date));
return stirngDate;
}
But the problem is I have date in db as 2014-05-21 , when I use getFormatedDoI() method it prints 21-00-2014. In fact for all the dates in place of month it displays 0. How can I get exact formated date.? and the database I am using is mysql. The date coming from MYSQL database.
Small mm is for minutes, capital MM is for month number, if you want to get month name you can use MMM, in your case use "dd-MM-yyy" instead of 'dd-mm-yyyy'.
public String getFormatedDoI() {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String stirngDate = null ;
if(insurance_date != null)
stirngDate = df.format((insurance_date));
return stirngDate;
}
Should solve your problem :)
mm takes minute.
If you want month then use MM.
so instead of DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
use : DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
See this documentation on date format.
try
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
instead of
DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
It should resolve
Use "dd-MM-yyyy" instead of "dd-mm-yyyy". The pattern "mm" stands for minutes not for month.
I've a String representing a date.
String date_s = "2011-01-18 00:00:00.0";
I'd like to convert it to a Date and output it in YYYY-MM-DD format.
2011-01-18
How can I achieve this?
Okay, based on the answers I retrieved below, here's something I've tried:
String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?
Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.
String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
Then use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
Or, when you're not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.
String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
Then use SimpleDateFormat#format() to format a Date into a String in a certain pattern.
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
See also:
Java string to date conversion
Update: as per your failed attempt which you added to the question after this answer was posted; the patterns are case sensitive. Carefully read the java.text.SimpleDateFormat javadoc what the individual parts stands for. So stands for example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.
Formatting are CASE-SENSITIVE so USE MM for month not mm (this is for minute) and yyyy
For Reference you can use following cheatsheet.
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
Examples:
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.
Addendum: "mm" in the format String is not the same as "MM". Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy. e.g.,:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormateDate {
public static void main(String[] args) throws ParseException {
String date_s = "2011-01-18 00:00:00.0";
// *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dt1.format(date));
}
}
Why not simply use this
Date convertToDate(String receivedDate) throws ParseException{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(receivedDate);
return date;
}
Also, this is the other way :
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();
or
Date requiredDate = df.format(new Date());
Using the java.time package in Java 8 and later:
String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);
[edited to include BalusC's corrections]
The SimpleDateFormat class should do the trick:
String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Please refer "Date and Time Patterns" here. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class DateConversionExample{
public static void main(String arg[]){
try{
SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");
SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetDateFormat.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
Other answers are correct, basically you had the wrong number of "y" characters in your pattern.
Time Zone
One more problem though… You did not address time zones. If you intended UTC, then you should have said so. If not, the answers are not complete. If all you want is the date portion without the time, then no issue. But if you do further work that may involve time, then you should be specifying a time zone.
Joda-Time
Here is the same kind of code but using the third-party open-source Joda-Time 2.3 library
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
String date_s = "2011-01-18 00:00:00.0";
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );
// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.
// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );
When run…
dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18
dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z
try
{
String date_s = "2011-01-18 00:00:00.0";
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date tempDate=simpledateformat.parse(date_s);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Output date is = "+outputDateFormat.format(tempDate));
} catch (ParseException ex)
{
System.out.println("Parse Exception");
}
You can just use:
Date yourDate = new Date();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);
It works perfectly!
public class SystemDateTest {
String stringDate;
public static void main(String[] args) {
SystemDateTest systemDateTest = new SystemDateTest();
// format date into String
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
System.out.println(systemDateTest.getStringDate());
}
public Date getDate() {
return new Date();
}
public String getStringDate() {
return stringDate;
}
public void setStringDate(String stringDate) {
this.stringDate = stringDate;
}
}
String str = "2000-12-12";
Date dt = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try
{
dt = formatter.parse(str);
}
catch (Exception e)
{
}
JOptionPane.showMessageDialog(null, formatter.format(dt));
You could try Java 8 new date, more information can be found on the Oracle documentation.
Or you can try the old one
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getDate(Date date, String dateFormat) {
DateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(date);
}
You can also use substring()
String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);
If you want a space in front of the date, use
String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);
private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof Date) {
value = dataFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};
remove one y form the format provide to:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
It should be:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
We can convert Today's date in the format of 'JUN 12, 2020'.
String.valueOf(DateFormat.getDateInstance().format(new Date())));
/**
* Method will take Date in "MMMM, dd yyyy HH:mm:s" format and return time difference like added: 3 min ago
*
* #param date : date in "MMMM, dd yyyy HH:mm:s" format
* #return : time difference
*/
private String getDurationTimeStamp(String date) {
String timeDifference = "";
//date formatter as per the coder need
SimpleDateFormat sdf = new SimpleDateFormat("MMMM, dd yyyy HH:mm:s");
TimeZone timeZone = TimeZone.getTimeZone("EST");
sdf.setTimeZone(timeZone);
Date startDate = null;
try {
startDate = sdf.parse(date);
} catch (ParseException e) {
MyLog.printStack(e);
}
//end date will be the current system time to calculate the lapse time difference
Date endDate = new Date();
//get the time difference in milliseconds
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
if (diffInDays >= 365) {
int year = (int) (diffInDays / 365);
timeDifference = year + mContext.getString(R.string.year_ago);
} else if (diffInDays >= 30) {
int month = (int) (diffInDays / 30);
timeDifference = month + mContext.getString(R.string.month_ago);
}
//if days are not enough to create year then get the days
else if (diffInDays >= 1) {
timeDifference = diffInDays + mContext.getString(R.string.day_ago);
}
//if days value<1 then get the hours
else if (diffInHours >= 1) {
timeDifference = diffInHours + mContext.getString(R.string.hour_ago);
}
//if hours value<1 then get the minutes
else if (diffInMinutes >= 1) {
timeDifference = diffInMinutes + mContext.getString(R.string.min_ago);
}
//if minutes value<1 then get the seconds
else if (diffInSeconds >= 1) {
timeDifference = diffInSeconds + mContext.getString(R.string.sec_ago);
} else if (timeDifference.isEmpty()) {
timeDifference = mContext.getString(R.string.now);
}
return mContext.getString(R.string.added) + " " + timeDifference;
}
Say you want to change 2019-12-20 10:50 AM GMT+6:00 to 2019-12-20 10:50 AM
first of all you have to understand the date format first one date format is
yyyy-MM-dd hh:mm a zzz and second one date format will be yyyy-MM-dd hh:mm a
just return a string from this function like.
public String convertToOnlyDate(String currentDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a ");
Date date;
String dateString = "";
try {
date = dateFormat.parse(currentDate);
System.out.println(date.toString());
dateString = dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
This function will return your desire answer. If you want to customize more just add or remove component from the date format.
you have some wrong:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
first :
should be
new SimpleDateFormat("yyyy-mm-dd");
//yyyy 4 not 5
this display 02011, but yyyy it disply 2011
second:
change your code like this
new SimpleDateFormat("yyyy-MM-dd");
i hope help you
java.time
In March 2014, modern date-time API* API supplanted the error-prone java.util date-time API and their formatting API, SimpleDateFormat. Since then it has been highly recommended to stop using the legacy API.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
You do not need DateTimeFormatter for formatting
You need DateTimeFormatter only for parsing your string but you do not need a DateTimeFormatter to get the date in the desired format. The modern Date-Time API is based on ISO 8601 and thus the toString implementation of java.time types return a string in ISO 8601 format. Your desired format is the default format of LocalDate#toString.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "2011-01-18 00:00:00.0";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDate, dtfInput);
// Alternatively,
// LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);
LocalDate date = ldt.toLocalDate();
System.out.println(date);
}
}
Output:
2011-01-18
ONLINE DEMO
Some important notes about the solution:
java.time made it possible to call parse and format functions on the Date-Time type itself, in addition to the traditional way (i.e. calling parse and format functions on the formatter type, which is DateTimeFormatter in case of java.time API).
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.
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");