Display current time in 12 hour format with AM/PM - java

Currently the time displayed as 13:35 PM
However I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM
The current code is as below
private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
formatDate.setTimeZone(userContext.getUser().getTimeZone());
model.addAttribute("userCurrentTime", formatDate.format(new Date()));
final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
/ FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
model.addAttribute("offsetHours",
offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
return "systemclock";
}

Easiest way to get it by using date pattern - h:mm a, where
h - Hour in am/pm (1-12)
m - Minute in hour
a - Am/pm marker
Code snippet :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Read more on documentation - SimpleDateFormat java 7

Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Java docs for SimpleDateFormat

use "hh:mm a" instead of "HH:mm a". Here hh for 12 hour format and HH for 24 hour format.
Live Demo

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
h is used for AM/PM times (1-12).
H is used for 24 hour times (1-24).
a is the AM/PM marker
m is minute in hour
Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.
Looks like basically everyone beat me to it already, but I digress

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);
Output:
11-Sep-13 12.25.15.375 PM

// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));
// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now()));
// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now()));

Using Java 8:
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));
The output is in AM/PM Format.
Sample output: 3:00 PM

tl;dr
Let the modern java.time classes of JSR 310 automatically generate localized text, rather than hard-coding 12-hour clock and AM/PM.
LocalTime // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now( // Capture the current time-of-day as seen in a particular time zone.
ZoneId.of( "Africa/Casablanca" )
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in our `LocalTime` object.
DateTimeFormatter // Class responsible for generating text representing the value of a java.time object.
.ofLocalizedTime( // Automatically localize the text being generated.
FormatStyle.SHORT // Specify how long or abbreviated the generated text should be.
) // Returns a `DateTimeFormatter` object.
.withLocale( Locale.US ) // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
) // Returns a `String` object.
10:31 AM
Automatically localize
Rather than insisting on 12-hour clock with AM/PM, you may want to let java.time automatically localize for you. Call DateTimeFormatter.ofLocalizedTime.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Here we get the current time-of-day as seen in a particular time zone. Then we generate text to represent that time. We localize to French language in Canada culture, then English language in US culture.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;
// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ; // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;
System.out.println( outputQuébec ) ;
// US
Locale locale_en_US = Locale.US ;
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;
System.out.println( outputUS ) ;
See this code run live at IdeOne.com.
10 h 31
10:31 AM

If you want current time with AM, PM in Android use
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());
If you want current time with am, pm
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();
OR
From API level 26
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);

Just replace below statement and it will work.
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
This will display the date and time

//To get Filename + date and time
SimpleDateFormat f = new SimpleDateFormat("MMM");
SimpleDateFormat f1 = new SimpleDateFormat("dd");
SimpleDateFormat f2 = new SimpleDateFormat("a");
int h;
if(Calendar.getInstance().get(Calendar.HOUR)==0)
h=12;
else
h=Calendar.getInstance().get(Calendar.HOUR)
String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";
The Output Like:TestReport27Apr3PM.txt

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
String sDate = "22-01-2019 13:35 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
sDate = displayFormat.format(date);
System.out.println("The required format : " + sDate);
} catch (Exception e) {}
}
}
- Using java 8
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main
{
public static void main(String[] args)
{
String pattern = "hh:mm:ss a";
//1. LocalTime
LocalTime now = LocalTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern(pattern)));
//2. LocalDateTime
LocalDateTime nowTime = LocalDateTime.now();
System.out.println(nowTime.format(DateTimeFormatter.ofPattern(pattern)));
}
}

To put your current mobile date and time format in
Feb 9, 2018 10:36:59 PM
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
you can show it to your Activity, Fragment, CardView, ListView anywhere by using TextView
` TextView mDateTime;
mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);
Date date = new Date();
String mStringDate = DateFormat.getDateTimeInstance().format(date);
mDateTime.setText("My Device Current Date and Time is:"+date);
`

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
("hh:mm:ss a") >>> Here if we don't use 'a' then 24hours will be appeared. so if we want to AM/PM in your time just add this format. if any confusion please let me know.

Related

How can I get a date to be put into input? Then how can I get it to make a due date based on an undetermined rental period inputed by the user? [duplicate]

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

Change time zone of exesting date in Java [duplicate]

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.

Why Calendar and SimpleDateFormat are showing a bad date?

I try to parse a date from a string but when I print it, it shows a bad date. My code:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String args[]) {
String some_date = "2017-12-31";
Calendar cal_aux = GregorianCalendar.getInstance();
System.out.println("set calendar: " + Integer.parseInt(some_date.substring(0, 4))
+ Integer.parseInt(some_date.substring(5, 7))
+ Integer.parseInt(some_date.substring(8, 10)));
cal_aux.set(Integer.parseInt(some_date.substring(0, 4)),
Integer.parseInt(some_date.substring(5, 7)),
Integer.parseInt(some_date.substring(8, 10)));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("sdf calendar: " + sdf.format(cal_aux.getTime()));
}
}
Console output:
set calendar: 20171231
sdf calendar: 2018-01-31 12:51:02
Why when I use the simple date format I'm getting 2018 instead of 2017?
Avoid the legacy date-time classes now supplanted by java.time classes. The problematic legacy classes have many design faults. One such fault is counting months as 0-11 rather than 1-12. This crazy counting is breaking your code.
Do not manipulate date-time values as strings. Use objects.
For that date-only value use LocalDate.
LocalDate ld = LocalDate.parse( "2017-12-31" ) ; // Or LocalDate.now() for today's date.
Generate a String by using a DateTimeFormatter.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;
20171231
Assign a time-of-day if desired.
LocalTime lt = LocalTime.of( 6 , 15 ) ;
LocalDateTime ltd = LocalDateTime.of( ld , lt ) ;
Apply a time zone if you want an actual moment, a specific point on the timeline.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
First, you set wrong date because the month range is 0-11. When you set 12 in month field, is january 2018 instead december 2017.
Second, you can simplify your program parsing the input string to formatted date and parsing this date to output formatted string. Here is an example:
String input = "20171231";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
System.out.println(outputFormat.format(inputFormat.parse(input)));
} catch (ParseException e) {
// Log error
}

Not able to convert EST to IST time in Java

Hi i am currently work on creating Desktop application using Swing.I was able to convert IST to EST time using Date class in java but not able to convert EST to IST time and it gives same EST time as IST time. Please find the below code .
ChangetoEST function is giving correct EST time from IST time.
ChangetoIST function is not giving correct IST time from EST time and showing given EST time as IST time.
public String changetoEST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
formatter.setTimeZone(tzInAmerica);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
public String changetoIST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInIndian = TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tzInIndian);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
The parse calls are done without you explicitly setting a time zone, which means that parsing is done using your default time zone.
Set the source time zone before parsing, parse, set time zone to target time zone, and format result.
E.g.
public static String istToEst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("Asia/Calcutta"),
TimeZone.getTimeZone("America/New_York"));
}
public static String estToIst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("Asia/Calcutta"));
}
private static String changeTimeZone(String dateInput, TimeZone sourceTimeZone,
TimeZone targetTimeZone) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
formatter.setTimeZone(sourceTimeZone);
Date date = formatter.parse(dateInput);
formatter.setTimeZone(targetTimeZone);
return formatter.format(date);
}
Test
String dateInput = "08/22/2016 02:21 AM";
System.out.println(dateInput);
System.out.println(istToEst("08/22/2016 02:21 AM"));
System.out.println(estToIst("08/22/2016 02:21 AM"));
Output
08/22/2016 02:21 AM
08/21/2016 04:51 PM
08/22/2016 11:51 AM
Set formatter to the source timezone before parsing (this is the step you are missing), then set it to the destination timezone before formatting, otherwise it parses it using the local timezone, which is IST for you.
Also you should just be able to return sDateInAmerica directly, you don't need to re-parse then re-format it a second time.
java.time
You are using troublesome old legacy date-time classes, now supplanted by the java.time classes.
We parse the input string as a LocalDateTime as it lacks any info about offset-from-UTC or time zone (offset plus rules for anomalies such as DST).
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/yyyy hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
Apply a time zone to get an actual moment on the timeline, a ZonedDateTime object.
ZoneId zNewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdtNewYork = ldt.atZone( zNewYork );
To see the same moment through the lens of another time zone, another wall-clock time, adjust into another ZoneId. Notice that we are not going through another LocalDateTime as the purpose of that class is to forget any information about offset or time zone. We want the opposite, to use the info about time zone to adjust wisely between zones. So while New York is behind UTC by four hours, India is ahead of UTC by five and a half hours. So we need a total of nine and a half hour adjustment, which may include a change in date.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtNewYork.withZoneSameInstant( zKolkata ); // Same simultaneous moments on the timeline.
Generate String
You can generate a String in any format you desire to represent the date-time value.
String output = zdtKolkata.format( f );
Generally better to let java.time automatically localize for you.
Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( l );
String output = zdtKolkata.format( f );

Change date format in a Java string

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

Categories

Resources