Changing date formats - java

I have the following code:
// OLD DATE
String date = "Mon, 06/07";
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = date.substring(date.length() - 5);
Date dateOld;
try {
dateOld = df.parse(strDate);
} catch (Exception e) {
e.printStackTrace();
}
String dateStr = df.format(dateOld);
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime dateNew = ZonedDateTime.now().with(monthDay);
// NEW DATE
System.out.println(dateNew.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'")));
Basically what I am trying to do is change Mon, 06/07 format to this format 2021-06-07T00:00:00Z.
What I have works, but it is really terrible. What would be a better way of doing it?

This is a little tricky as you need to make some assumptions
The year, as it's not specified in the original format
TimeZone, as it's not specified at all (the final output seems to point to UTC)
The first thing your need to do, is parse the String input into a LocalDate (you could just go straight to ZonedDate, but this is where I started)
String date = "Mon, 06/07";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("E, M/d")
.parseDefaulting(ChronoField.YEAR, 2021)
.toFormatter(Locale.US);
LocalDate ld = LocalDate.parse(date, parseFormatter);
Then you need to convert that to LocalDateTime
LocalDateTime ldt = ld.atStartOfDay();
And then, to a ZonedDateTime. Here' I've assumed UTC
//ZoneId zoneId = ZoneId.systemDefault();
//ZonedDateTime zdt = ldt.atZone(zoneId);
OffsetDateTime zdt = ldt.atOffset(ZoneOffset.UTC);
And finally, format the result to your desired format
String formatted = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(formatted);
Which, for me, prints...
2021-06-07T00:00:00Z
A lot of time and effort has gone into the new Date/Time APIs and you should make the time to try and learn them as best you can (I'm pretty rusty, but with a little tinkering, got to a result)
Maybe start with Date/Time trails

A solution use Calendar, Date and SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM/dd", Locale.getDefault());
try {
Date oldDate = sdf.parse("Mon, 06/07");
Calendar calendar = Calendar.getInstance();
int savedYear = calendar.get(Calendar.YEAR);
if (oldDate != null) {
calendar.setTime(oldDate);
calendar.set(Calendar.YEAR, savedYear);
sdf.applyPattern("yyyy-MM-dd'T00:00:00Z'");
System.out.println(sdf.format(calendar.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}

Related

How to split the full date format in date and time?

I have a lot of Strings in the format shown my example that I have to parse. I'm trying to determine which of the Strings are today.
My problem is, that the time is almost there and I just need to compare that date.
Next I want to check if time is between two timestamps "HH:mm:ss" with .after and .before, but there is the problem, that the date is almost there.
How do I split that parsed format in date and time to handle each in its own way?
I'm working in Android Studio, if that's relevant.
String dtStart = "2016-05-23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if (new Date().equals(format.parse(dtStart)) ) System.out.println("true");
else System.out.println("false");
list.add(new LatLng(lat, lng));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.time
Use the java.time classes built into Java 8 and later.
Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport, and further adapted to Android in ThreeTen-ABP.
String dateToParse = "2016-05-23 07:24:59";
LocalDateTime dateTime = LocalDateTime.parse(dateToParse, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDate localDate = dateTime.toLocalDate();
LocalTime localTime = dateTime.toLocalTime();
// Compare here to your date & time
You can easily achieve it by using the SimpleDateFormat like that:
//Houres - seconds
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Years - days
Date hoursAndMinutes = timeFormat.parse(dtStart);
Date yearsMonthsDays = dateFormat.parse(dtStart);
That way, you only get the hours, minutes and seconds of your date.
Then, you can do the same for just the year and month and compare it afterwards.
And just to be complete, here's how you'd do it using the Joda date time library and the toLocalDate() and toLocalTime() method.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime today = new DateTime();
DateTime start = formatter.parseDateTime(dtStart);
if (today.toLocalDate().compareTo(start.toLocalDate()) != 0) {
System.out.println("true");
} else {
System.out.println("false");
}
if (today.toLocalTime().compareTo(start.toLocalTime()) > 0) {
...
}
thx for help and sry i forgot to say i'm on android studio..
i found my solution here: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
String dtStart = "2016/05/23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date dtStartOK = format.parse(dtStart);
String stringDate = DateFormat.getDateTimeInstance().format(dtStartOK);
System.out.println(stringDate);
System.out.println(DateFormat.getDateInstance().format(dtStartOK));
System.out.println(DateFormat.getTimeInstance().format(dtStartOK));
} catch (ParseException e) {
//Handle exception here, most of the time you will just log it.
e.printStackTrace();
}
gives me:
23.05.2016 07:24:59
23.05.2016
07:24:59

Java Get One Day Before Specific Date

I have a String expired date. But I need to perform some SQL statement the day before expired date falls. I get my expired date and by:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiredDate = null;
String currentDate = dateFormat.format(new Date());
Calendar cal = Calendar.getInstance();
try {
cal.setTime(dateFormat.parse(loanDate));
cal.add(Calendar.WEEK_OF_YEAR, 2);
expiredDate = dateFormat.format(cal.getTimeInMillis());
cal.add(Calendar.WEEK_OF_YEAR, -2);
} catch (ParseException e) {
e.printStackTrace();
}
Then, I got an if statement to perform SQL statement:
if(expiredDate.equals(currentDate)){
promptExtensionDialog();
}
What I am trying to achieve is for the if statement, instead of the expiredDate itself, I need to get one day before the expired date and compare with the current date. I wonder how to achieve this?
Thanks in advance.
EDIT
try {
cal.setTime(dateFormat.parse(expiredDate));
cal.add(Calendar.DATE, -1);
expiredDate = dateFormat.format(cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(LoanBook.this,
expiredDate, Toast.LENGTH_LONG)
.show();
This returns me the next date instead of previous date. Do you have any ideas?
Using Java's (pre-8) built-in Date and Time API will eat you alive. Use JodaTime for complex DateTime manipulations.
Getting the previous day is as simple as this.
DateTime dateTime = new DateTime();
System.out.println(dateTime);
System.out.println(dateTime.minusDays(1));
If you don't want any external libraries:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2014-10-28";
Date date = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
Date yesterday = calendar.getTime();
System.out.println(yesterday);
System.out.println(date);
Have you tried JodaTime? It is a fantastic library to do date manipulation easily. In fact, a lot of Java 8 date handling are derived from JodaTime.
For your needs, you could do something like:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dt = formatter.parseDateTime(expiredDate);
DateTime dayBefore = dt.minusDays(1);
The other two answers are basically correct. But they omit the crucial issue of time zones and start of day. If you want all of yesterday, do something like the following.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime yesterdayStart = now.minusDays( 1 ).withTimeAtStartOfDay();
Convert to a java.sql.Timestamp.
java.sql.Timestamp ts = new java.sql.Timestamp( yesterdayStart.getMillis() );

Calendar date to yyyy-MM-dd format in java

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Java Date Formatter

I am getting date format as "YYYY-mm-dd hh:mm" as formatter object.
How can I format the input formatter object to get only "YYYY-mm-dd";?
I am getting date format as
"YYYY-mm-dd hh:mm" as formatter
object. How can i format the input
formatter object to get only
"YYYY-mm-dd";
You can not have date as YYYY-mm-dd it should be yyyy-MM-dd. To get date in yyyy-MM-dd following is the code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Format formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date;
try {
date = (Date)((DateFormat) formatter).parse("2011-04-13 05:00");
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
System.out.println(s);
} catch (ParseException e) {
e.printStackTrace();
}
Use SimpleDateFormat
String myDateString = "2009-04-22 15:51";
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(outFormat.format(inFormat.parse(myDateString)));
If you're getting a date in the format "YYYY-mm-dd hh:mm" and you want it as "YYYY-mm-dd" I suggest you just use inputDate.substring(0, 10).
In either way, beware of potential Y10k bugs :)
Following sample formate date as yyyy-MM-dd in Java
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();
System.out.println("Now: "+formatter.format(now.getTime()) );
Yes, SimpleDateFormat is what you are looking for
http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/builds/latest/html/en/api/java/text/SimpleDateFormat.html
SimpleDateFormat is what you're looking for.
Try this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Use this code:
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
System.out.println("formatted time==>" + formattedDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Other answers such as the one by user2663609 are correct.
As an alternative, the third-part open-source replacement for the java.util.Date/Calendar classes, Joda-Time, includes a built-in format for your needs.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String stringIn = "2011-04-07";
// Returns a formatter for a full date as four digit year, two digit month of year, and two digit day of month (yyyy-MM-dd).
DateTimeFormatter formatter = ISODateTimeFormat.date().withZone( DateTimeZone.forID( "Europe/London" ) ).withLocale( Locale.UK );
DateTime dateTime = formatter.parseDateTime( stringIn ).withTimeAtStartOfDay();
String stringOut = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime.toString() );
System.out.println( "stringOut: " + stringOut );
When run…
dateTime: 2011-04-07T00:00:00.000+01:00
stringOut: 2011-04-07
This question has so many good answers !! , here comes another one more generic solution
public static String getDateInFormate(String oldFormate , String newFormate , String dateToParse){
//old "yyyy-MM-dd hh:mm"
//new yyyy-MM-dd
//dateTopars 2011-04-13 05:00
String formatedDate="";
Format formatter = new SimpleDateFormat();
Date date;
try {
date = (Date)((DateFormat) formatter).parse(dateToParse);
formatter = new SimpleDateFormat(newFormate);
formatedDate = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String strDate = entry_date;
System.out.println("strDate*************"+strDate);
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date yesterday =subtractDay( date);
String requiredDate = df.format(yesterday);
System.out.println("110 days before*******************"+requiredDate);
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -110);`enter code here`
return cal.getTime();
}
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
For parsing input define a formatter:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ROOT);
Parse:
String input = "2019-01-21 23:45";
LocalDateTime dateTime = LocalDateTime.parse(input, FORMATTER);
System.out.println(dateTime);
Output so far:
2019-01-21T23:45
Format output:
String output = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(output);
2019-01-21
Tutorial link
Trail: Date Time (The Java™ Tutorials) explaining how to use java.time.

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