I have a string where contain date and time with format like this
"2020-09-20-08-40"
i try to convert that string to date with format "dd-MM-yyyy HH:mm" and print that in a textview. I saw other people try convert with this way
String dateString = "2020-09-20-08-40"
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = format1.parse(dateString);
String dateFinal = format2.format(date);
t_date.setText(dateFinal);
when i try this way, i got error java.lang.IllegalArgumentException
How to solve this?
tl;dr
LocalDateTime.parse(
"2020-09-20-08-40" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" )
)
See code run live at IdeOne.com.
2020-09-20T08:40
Details
Avoid using terrible legacy date-time classes. Use only java.time classes.
Define a formatting pattern to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" ) ;
Parse your input text.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Tip: Educate the publisher of your data about the ISO 8601 standard for exchanging date-time values as text. No need to be inventing such formats as seen in your Question. The java.time classes use the standard formats by default when parsing/generating strings, so no need to specify a formatting pattern.
Thanks to #Nima Khalili and #Andre Artus answer, i can solve this. My code will look this
String dateString = "2020-09-20-08-40"
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
format1.setTimeZone(TimeZone.getTimeZone("GMT + 7"));
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date;
try {
date = format1.parse(dateString);
String dateFinal = format2.format(date);
t_date.setText(dateFinal);
} catch (ParseException e) {
e.printStackTrace();
}
If you have a date+time like "2020-09-20-08-40" then your format should reflect that, e.g.
"yyyy-MM-dd-HH-mm"
Related
No matter what I do its not working. I want to have it in dd/mm/yyyy I have tried and unable to get it done.Tried with JAVA 8 api of Instant localdate localtime localdatetime too.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
Timestamp ts = new Timestamp(time);
System.out.println(ts);
Prints like this 2007-09-23 00:00:00.0;
TimeStamp has its own format, so you need to format it as per your needs
Try,
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = f.parse("23/12/2007 00:00:00");
String strDate = f.format(date);
System.out.println("Current Date = "+strDate);
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
➥ Never use java.util.Date, java.sql.Date, nor java.sql.Timestamp.
For a date only, without time-of-day and without time zone, use LocalDate.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String input = "23/09/2007" ;
LocalDate ld = LocalDate.parse( input , f ) ;
Generate text in standard ISO 8601 format.
String output = ld.toString() ;
Generate text in that same custom format.
String output = ld.format( f ) ;
I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
My Question is, how to tweak this code so it will work for below scenarios ex,
my s string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
right now it fails if I don't pass the ms.. Thanks!
Different types
String s = "2019-04-23 06:57:00";
String s = "2019-04-23";
These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.
LocalDateTime.parse
To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.
LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
The fractional second parses by default as well.
LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
See this code run live at IdeOne.com.
ldt1.toString(): 2019-04-23T06:57
ldt2.toString(): 2019-04-23T06:57
LocalDate.parse
Your date-only input already complies with ISO 8601.
LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-04-23
Date with time-of-day
You can strip out the time-of-day from the date.
LocalDate ld = ldt.toLocalDate() ;
And you can add it back in.
LocalTime lt = LocalTime.parse( "06:57:00" ) ;
LocalDateTime ldt = ld.with( lt ) ;
Moment
However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.
For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.
Avoid legacy date-time classes
The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.
In case of you have optional parts in pattern you can use [ and ].
For example
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 7 years ago.
I want to convert system date and time in 2016-02-14T15:50:39Z format. How to achieve using java?
tl;dr
Instant.now()
.toString()
2018-01-23T01:23:45.678901Z
Details
The other answers use old outmoded classes.
ISO 8601
Your desired format complies with the ISO 8601 standard.
The Z on the end stands for Zulu which means UTC.
java.time
In Java 8 and later, use the built-in java.time framework.
The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values.
Instant
An Instant is a moment on the time line in UTC. Its now method gets the current moment. As of Java 8 Update 74 that now method gets the current moment with millisecond resolution but future versions may get up to the full nanosecond resolution which can fit in an Instant.
The Instant::toString method generates a String just as you desire, using groups of digits (0, 3, 6, or 9) as needed for the fractional second.
String output = Instant.now().toString(); // Example: 2016-02-14T15:50:39.123Z
Truncate fractional second
If do not care about the fraction of a second, as seen in your Question’s example, truncate with a call to with, passing the ChronoField.NANO_OF_SECOND enum.
String output = Instant.now().with( ChronoField.NANO_OF_SECOND , 0 ).toString(); // Example: 2016-02-14T15:50:39Z (no '.123' at end)
Even simpler, call truncatedTo method, passing a ChronoUnit.SECONDS enum.
String output = Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString();
If you want to truncate to whole minute rather than whole second, see this other Question.
Try this code:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args)
{
Date dt=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String formattedDate = formatter.format(dt);
System.out.println(formattedDate);
}
}
You can try several others date formats here.
use simple date format below is example :
Date curDate = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
try {
Date strToDate = format.parse(DateToStr);
System.out.println(strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
I have a string like this 2013-10-22T01:37:56. I Need to change this string into UTC Date format like this MM/dd/yyyy KK:mm:ss a. I have tried some code but it is not returning the UTC datetime.
My code is
String[] time = itsAlarmDttm.split("T");
String aFormatDate = time[0]+ " "+time[1];
String aRevisedDate = null;
try {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date dateObj = sdf.parse(aFormatDate);
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
} catch (ParseException e) {
itsLogger.error("Error occured in Parsing the Data Time Object: " +e.getMessage());
} catch (Exception e) {
itsLogger.error("Error occured in Data Time Objecct: " +e.getMessage());
}
I am getting the output is MM/dd/yyyy KK:mm:ss a format. But Not UTC time format.
How to solve this issue?
Try this... Worked for me and printed 10/22/2013 01:37:56 AM Ofcourse this is your code only with little modifications.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
Try to format your date with the Z or z timezone flags:
new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
What Time Zones?
No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.
ISO 8601
Your input string is in ISO 8601 format, except that it lacks an offset from UTC.
Joda-Time
Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.
String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();
As for generating string representations in other formats, search StackOverflow for "Joda format".
java.time
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.
DateFormat inFm = new SimpleDateFormat("d-MMM-y");
DateFormat outFm = new SimpleDateFormat("d-M-yyyy");
Date date = inFm.parse("14-Dec-2010");
String output = outFm.format(date);
Generally, you should use a datetime type like Date internally, then transform to String at output time.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
/**
* #param args
*/
public static void main(String[] args) {
Date date = new Date("14-Dec-2010"); //deprecated. change it to your needs
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(date));
}
}
I think this SQL convert should work
SELECT CONVERT(datetime,'14-Dec-2010',105)
DateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date= format.parse("14-Dec-2010");
This is how you will get Date Object now you can print it in any format.
Note: month starts from 0 , so for Dec it would be 11
Here is working IDE One demo
Document
Avoid using the troublesome old date-time classes bundled with the earliest versions of Java. They are poorly designed and confusing.
java.time
The old classes are supplanted by the java.time framework.
For a date-only value without time of day and without time zone use LocalDate class.
Parse the String input using DateTimeFormatter.
String input = "14-Dec-2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
To generate a String in another format, define another formatter.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
String output = localDate.format( formatter2 );
Better yet, let DateTimeFormatter automatically localize.
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
String output = localDate.format( f ); // Generates String in a localized format.
SQL
For SQL just pass objects, do not use strings. Pass LocalDate via setObject on a PreparedStatement if your JDBC driver complies with the JDBC 4.2 spec.
myPrepStmt.setObject( localDate );
If not, fall back to the old java.sql.Date class by using new conversion methods added to the old classes.
java.sql.Date sqlDate = java.sql.Date.from( localDate );
myPrepStmt.setDate( sqlDate );