问题
I need to get the Date of the current time with the following format "yyyy-MM-dd'T'HH:mm:ss"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
I know how to format a Date using SimpleDateFormat. At the end I get a String. But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?
If I just return the Date, it is a Date but it is not properly formatted:
Timestamp ts = new Timestamp(new Date().getTime());
EDIT: Unfortunately I need to get the outcome as a Date, not a String, so I cannot use sdf.format(New Date().getTime()) as this returns a String. Also, the Date I need to return is the Date of the current time, not from a static String. I hope that clarifies
回答1:
But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?
Since you know the DateTime-Format, it's actually pretty easy to format from Date to String and vice-versa. I would personally make a separate class with a string-to-date and date-to-string conversion method:
public class DateConverter{
public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public static Date convertStringToDate(final String str){
try{
return DATE_FORMAT.parse(str);
} catch(Exception ex){
//TODO: Log exception
return null;
}
}
public static String convertDateToString(final Date date){
try{
return DATE_FORMAT.format(date);
} catch(Exception ex){
//TODO: Log exception
return null;
}
}
}
Usage:
// Current date-time:
Date date = new Date();
// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);
// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);
回答2:
Try this way
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = sdf.parse("2016-03-10....");
回答3:
use my code, I hope it's works for you......
SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
String str_date=dateFormat.format(new Date());
回答4:
tl;dr
ZonedDateTime.now() // Capture the current moment as seen by the people of a region representing by the JVM’s current default time zone.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).
java.time
The modern approach uses the java.time classes.
Capture the current moment in UTC.
Instant instant = Instant.now() ;
View that same moment through the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
You want to generate a string representing this value in a format that lacks any indication of time zone or offset-from-UTC. I do not recommend this. Unless the context where read by the user is absolutely clear about the implicit zone/offset, you are introducing ambiguity in your results. But if you insist, the java.time classes predefine a formatter object for that formatting pattern: DateTimeFormatter.ISO_LOCAL_DATE_TIME.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
回答5:
To format a data field do this
Date today = new Date();
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String date2= DATE_FORMAT.format(today);
Date date;
try {
date = DATE_FORMAT.parse(date2);
setDate(date); //make use of the date
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above works for me perfectly.
回答6:
a parse method should be available to you. Use intellisense to check what methods your objects have :) Or simply look at the javadoc, most IDE's have an option to open the java files.
String dateString = "2016-01-01T00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(dateString);
回答7:
Try this:
LocalDateTime ldt = Instant.now()
.atZone(ZoneId.systemDefault())
.toLocalDateTime()
回答8:
If you want String to Date conversion, you need to parse Date in String format using DateFormat. This is an example -
String target = "2016-03-10T15:54:49";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date result = df.parse(target);
回答9:
public String getCurrentDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// get current date time with Date()
Date date = new Date();
return dateFormat.format(date);
}
回答10:
Time Format should be same or else get time parser exception come
String dateString = "03/26/2012 11:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch t(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(convertedDate);
回答11:
Yes u can :) you can convert back a String to a Date.
This method will help you: Date parse(String date);
It returns Date class object. You just have to pass the date in String format in this method.
import java.text.*;
import java.util.*;
class Test {
public static void main(String[] args) throws Throwable {
String date = "2016-03-10T04:05:00";
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = s.parse(date);
System.out.println(d);
}
}
来源:https://stackoverflow.com/questions/35913647/format-a-date-and-returning-a-date-not-a-string