How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)
Related
I have a String that formatted MM/dd. I would like to convert it to a Date in format yyyy-MM-dd'T'HH:mm:ss.SSZ.
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = "06/05";
Date date = new Date();
date = df.parse(strDate);
This makes it a Date, but in the original format.
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ").format(date));
This returns the correct month and day, but nopthing else.
1970-06-05T00:00:00.00-0400
Any idea how I can make it return
CURRENT_YEAR-06-05TCURRENT_TIME
In the question, the date format pattern indicates a desire for 2-digit fractional seconds. SimpleDateFormat cannot do that.
The newer Java 8 Time API can, and you should be using that anyway.
If you're running on Java 6 or 7, get the ThreeTen-Backport library.
To parse a MM/dd formatted string and get a full timestamp with current year and time-of-day, in the default time zone, use the following code:
String strDate = "06/05";
MonthDay monthDay = MonthDay.parse(strDate, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime date = ZonedDateTime.now().with(monthDay);
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ")));
Sample Output
2020-06-05T14:52:48.45-0400
I recommend to make use of java.time package. There you go:
var ds = "01/12";
var df = java.time.format.DateTimeFormatter.ofPattern("MM/dd");
var dt = java.time.MonthDay.from(df.parse(ds)).adjustInto(java.time.LocalDateTime.now());
Then you can convert dt to java.util.Date or whatever you like. Or simply use one of java.time formaters to get the desired output.
You are creating a date with only month and day
If you want to use the current year and time, you can create a calendar object and edit the month and day
For something this simple I suggest a different approach, get current time then set month and day from the original string THEN format.
String str = "08/09";
String[] split = str.split("/");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(split[0]));
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(split[1]));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(calendar.getTime()));
String strDate = "06-05";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-"+strDate+"'T'HH:mm:ss.SSZ");
System.out.println(sdf.format(new Date()));
the output:
2020-06-05T23:00:45.306+0400
I have the following scenario :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));
gives an output
Tue May 31 00:00:00 SGT 2011
but I want the output to be
31/05/2011
I need to use parse here because the dates need to be sorted as Dates and not as String.
Any ideas ??
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
You need to go through SimpleDateFormat.format in order to format the date as a string.
Here's an example that goes from String -> Date -> String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
If you want to simply output a date, just use the following:
System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());
As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:
String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());
You can also customize your output by following the Java API on Date/Time conversions.
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).
This will help you.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
print (df.format(new Date());
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
This looks more compact. Finishes in a single line.
import org.apache.commons.lang3.time.DateFormatUtils;
System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));
Need to format this String 2017-08-01T15:43:45+0530 to 2017-08-01T15:43:45+05:30 using a particular date format. Tried with yyyy-MM-dd'T'HH:mm:ssZZ. Did not work..
Date modified = aemPage.getProperties().get(cq:lastModified, Date.class);
private DateFormat seoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
String formattedDate = seoDateFormat.format(modified));
You need three X to get off set like
Sign TwoDigitHours : Minutes
I suggest to use OffsetDateTime if you are working with java8 or higher:
String input = "2017-08-01T15:43:45+0530";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
OffsetDateTime offsetDateTime = OffsetDateTime.parse(input, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println(offsetDateTime.format(formatter)); // 2017-08-01T15:43:45+05:30
Since 2017-08-01T15:43:45+05:30 is ISO_OFFSET_DATE_TIME, you can also just use:
String outPut = offsetDateTime.toString();
Update:
If you want to use SimpleDateFormat, try:
String input = "2017-08-01T15:43:45+0530";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
System.out.println(formatter.format(date));
But this only works when your system's offset is 0530 since Date does not hold time zone information.
I have this code and I want to print out the time as String without the 'T' character between date and time.
String datetime4 =new StringBuilder().append(date4).append(time4).toString();
DateTime newdt=new DateTime(datetime4);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
newdt = formatter.parseDateTime(datetime4);
System.out.println(newdt);
Notice that date4 and time4 are String variables.
It will print:
2017-11-04T11:23:00.000+02:00
One way of doing it:
String date4 = "2017-02-02";
String time4 = "12:00:00";
//To parse it to Temporal object
DateTime dateTime = DateTime.parse(date4 +"T"+ time4);
// to output it as String in a prefered format (Thanks #Hugo)
System.out.println(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
If you prefer Java 8 you will need to use formatter I think, LocalDateTime doesn't overload toString in the same way as JodaTime.
But not sure why you want to do this? seems like just appending both date and time is enough? Anyway if you want to parse to the date you need to put T as is needed to pass it as a valid date time format to DateTime as well as LocalDateTime if using Java8, then you can reformat it as you wish.
String date4 = "2017-02-02";
String time4 = "12:00:00";
LocalDateTime dateTime = LocalDateTime.parse(date4 +"T"+ time4);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Using Java 8 LocalDateTime;
LocalDateTime dateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
DateTimeFormatter desiredFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
dateTime = LocalDateTime.parse("2017-06-01T12:10:10", formatter);
System.out.println(desiredFormat.format(dateTime));
When you do:
System.out.println(newdt);
You're printing the newdt variable, and internally println calls the toString() method on the object.
As this variable's type is DateTime, this code outputs the result of newdt.toString(). And Datetime.toString() method uses a default format that contains the "T".
If you want the output String to have a different format, you can do something like this:
System.out.println(newdt.toString("yyyy-MM-dd HH:mm:ss"));
The output will be:
2017-11-04 11:23:00
(without the "T")
You can use this version of toString with any pattern accepted by DateTimeFormatter.
You can also create another DateTimeFormatter for the format you want:
DateTimeFormatter withoutT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(withoutT.print(newdt));
The output will be the same, it's up to you to choose.
I used following code to convert string to date but it is applying timezone of device while conversion.
I don't need this but I want same date/time from that string like
String = "2009-07-31 07:59:17.427"
Date = 2009-07-31 07:59:17.427
Date formatter = new Date(HttpDateParser.parse("2009-07-31 07:59:17.427"));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strCustomDateTime = dateFormat.format(formatter);
You may take in account default timezone offset to date you get after parsing:
public static String StringToDate(String dateToParse) {
Date formatter = new Date(HttpDateParser.parse(dateToParse));
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
int offset = TimeZone.getDefault().getRawOffset();
formatter.setTime(formatter.getTime() + offset);
String strCustomDateTime = dateFormat.format(formatter);
return strCustomDateTime;
}
What is the problem, exactly? You are trying to convert "2009-07-31 07:59:17.427" into a point in time, but, this does not specify a unique point in time -- without a timezone. So you do need a timezone, and the library is necessary picking one, the platform's current timezone.
If the problem is you wish to specify a different time zone, then call DateFormat.setTimeZone():
format.setTimeZone(TimeZone.getTimeZone("your time zone"));