String nDate;
String dateTemp;
int i;
nDate = kb.nextLine();
String[] temp = nDate.split("-");
int numDate = Integer.parseInt(String.valueOf(temp));
im having issues with the (temp) part in the last line. If for example my input is "06-21-2020", what I want to happen is it becomes "06212020"
Use replace() instead of split(). To further explain, String.valueOf() does not take an array of Strings.
String temp = nDate.replace("-","");
int numDate Integer.parseInt(temp);
java.time
The answer by Phaelax z is spot-on for your specific requirement.
However, I recommend you parse the date string to LocalDate and format it as you wish.
You will get much more than the required conversion e.g. just think of finding the name of the day on 06-21-2020 or something like converting to some other format e.g. Sun 21 June 2020. All such requirements can be easily done using the in-built API as shown in the following demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String nDate = "06-21-2020";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse(nDate, dtfInput);
DateTimeFormatter dtfOutput1 = DateTimeFormatter.ofPattern("MMdduuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput2 = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput3 = DateTimeFormatter.ofPattern("EEE dd MMM uuuu", Locale.ENGLISH);
System.out.println(dtfOutput1.format(date));
System.out.println(dtfOutput2.format(date));
System.out.println(dtfOutput3.format(date));
}
}
Output:
06212020
21/06/2020
Sun 21 Jun 2020
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Related
I get a timestamp in the format "20210908094049.884Z". This is the last modify timestamp from an LDAP object. I use Spring Boot Ldap. I have no clue how to parse this String in a Datetime like dd.MM.yyyy HH:mm.
Can anyone help me please?
Here is an example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Creating new simple date formatter with the format you've given
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
// Defining the input date
String inputDate = "20210908094049.884Z";
// Parsing the date, catching the parse exception if date is malformatted
Date date = null;
try {
// Date ends on a Z, we remove this Z (Z is for timezone UTC +0:00)
date = format.parse(inputDate.replace("Z", ""));
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Giving following output:
Wed Sep 08 09:40:49 CEST 2021
Edit:
Here another even better solution from Ole V.V.
import java.time.Instant;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
Instant instant = DateTimeFormatter
// Defining pattern to parse
.ofPattern("yyyyMMddHHmmss.SSSXX")
// Defining input to parse with pattern
.parse("20210908094049.884Z", Instant::from);
System.out.println(instant);
}
}
Output is an instant with value:
2021-09-08T09:40:49.884Z
java.time
I recommend that you use java.time, the modern Java date and time API, for your work with timestamps.
The LDAP timestamp format has a number of allowed variations (see the link at the bottom). The following formatter takes many of them into account, not all of them.
private static final DateTimeFormatter LDAP_PARSER = new DateTimeFormatterBuilder()
.appendPattern("uuuuMMddHHmmss")
.optionalStart()
.appendPattern("[.][,]")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, false)
.optionalEnd()
.appendPattern("[XX][X]")
.toFormatter(Locale.ROOT);
With this formatter we may for example parse your string into an OffsetDateTime:
String ldapTimestampString = "20210908094049.884Z";
OffsetDateTime timestamp = OffsetDateTime.parse(ldapTimestampString, LDAP_PARSER);
System.out.println(timestamp);
Output is:
2021-09-08T09:40:49.884Z
Formatting
To convert the timestamp to a string containing date and time you need to decide on a time zone for that since it is never the same date nor the same time in all time zones.
Use this formatter:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
Then do:
ZoneId zone = ZoneId.of("Pacific/Tarawa");
ZonedDateTime dateTime = timestamp.atZoneSameInstant(zone);
String formattedDateTime = dateTime.format(FORMATTER);
System.out.println(formattedDateTime);
08.09.2021 21:40
Links
Oracle tutorial: Date Time explaining how to use java.time.
GeneralizedTime on ldapwiki defining the LDAP timestamp format.
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?
String date = "2010-08-25";
String time = "00:00";
Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?
private static Date date(final String date,final String time) {
final Calendar calendar = Calendar.getInstance();
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String[] hm = time.split(":");
int hour = Integer.parseInt(hm[0]);
int minute = Integer.parseInt(hm[1]);
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d = calendar.getTime();
String dateString= dateFormat.format(d);
Date result = null;
try {
result = (Date)dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
What's wrong in this code?
You seem to be expecting the returned Date object to know about the format you've parsed it from - it doesn't. It's just an instant in time. When you want a date in a particular format, you use SimpleDateFormat.format, it's as simple as that. (Well, or you use a better library such as Joda Time.)
Think of the Date value as being like an int - an int is just a number; you don't have "an int in hex" or "an int in decimal"... you make that decision when you want to format it. The same is true with Date.
(Likewise a Date isn't associated with a specific calendar, time zone or locale. It's just an instant in time.)
How did you print out the return result? If you simply use System.out.println(date("2010-08-25", "00:00") then you might get Sat Sep 8 00:00 PDT 2010 depending on your current date time format setting in your running machine. But well what you can do is:
Date d = date("2010-08-25", "00:00");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d));
Just curious why do you bother with this whole process as you can simple get the result by concatenate your initial date and time string.
just use SimpleDateFormat class
See
date formatting java simpledateformat
The standard library does not support a formatted Date-Time object.
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT
2010". But I expected to get the date in the following format
"yyyy-MM-dd HH:mm".
The standard Date-Time classes do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:
For the modern Date-Time API: java.time.format.DateTimeFormatter
For the legacy Date-Time API: java.text.SimpleDateFormat
About java.util.Date:
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date(); // In your case, it will be Date date = date("2010-08-25", "00:00");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
// sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); // For a timezone-specific value
String strDate = sdf.format(date);
System.out.println(strDate);
Your function, Date date(String, String) is error-prone.
You can simply combine the date and time string with a separator and then use SimpleDateFormat to parse the combined string e.g. you can combine them with a whitespace character as the separator to use the same SimpleDateFormat shown above.
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
Note that using a separator is not a mandatory requirement e.g. you can do it as sdf.parse(date + time) but for this, you need to change the format of sdf to yyyy-MM-ddHH:mm which, although correct, may look confusing.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Date date = date("2010-08-25", "00:00");
String strDate = sdf.format(date);
System.out.println(strDate);
}
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
}
Output:
2010-08-25 00:00
ONLINE DEMO
Switch to java.time API.
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*.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = localDateTime("2010-08-25", "00:00");
// Default format i.e. the value of ldt.toString()
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ENGLISH);
String strDate = dtf.format(ldt);
System.out.println(strDate);
}
private static LocalDateTime localDateTime(final String date, final String time) {
return LocalDateTime.of(LocalDate.parse(date), LocalTime.parse(time));
}
}
Output:
2010-08-25T00:00
2010-08-25 00:00
ONLINE DEMO
You must have noticed that I have not used DateTimeFormatter for parsing the String date and String time. It is because your date and time strings conform to the ISO 8601 standards. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
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.
I'm surprise you are getting different date outputs on the different computers. In theory, SimpleDateFormat pattern "H" is supposed to output the date in a 24h format. Do you get 11:45pm or 11:45am?
Although it should not affect the result, SimpleDateFormat and Calendar are Locale dependent, so you can try to specify the exact locale that you want to use (Locale.US) and see if that makes any difference.
As a final suggestion, if you want, you can also try to use the Joda-Time library (DateTime) to do the date manipulation instead. It makes it significantly easier working with date objects.
DateTime date = new DateTime( 1991, 10, 13, 23, 39, 0);
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm").format( date.toDate());
DateTime newDate = DateTime.parse( dateString, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
I have this String date="2021-04-25T18:54:18" and i should to format like that: HH:mm ,dd mmm yyyy
I tried this
String date="2021-04-25T18:54:18";
Date format= null;
try {
format = new SimpleDateFormat("HH:mm, yyyy-MM-dd'T", Locale.ENGLISH).parse(date);
holder.tvDate.setText(format.toString());
} catch (ParseException e) {
e.printStackTrace();
}
But does not work
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .
Using modern date-time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-04-25T18:54:18";
LocalDateTime ldt = LocalDateTime.parse(strDateTime);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("HH:mm ,dd MMM yyyy", Locale.ENGLISH);
String output = dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
18:54 ,25 Apr 2021
Learn more about the modern date-time API from Trail: Date Time.
Using the legacy API:
You need two formatters: one for input pattern and one for output pattern. You didn't need two formatters in the case of the modern API because the modern API is based on ISO 8601 and your date-time string is already in this format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "2021-04-25T18:54:18";
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Date date = sdfInput.parse(strDateTime);
SimpleDateFormat sdfOutput = new SimpleDateFormat("HH:mm ,dd MMM yyyy", Locale.ENGLISH);
String output = sdfOutput.format(date);
System.out.println(output);
}
}
Output:
18:54 ,25 Apr 2021
* 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.
You are missing 1 step. SimpleDateFormat can only parse dates in the format you specify.
You are trying to parse a "yyyy-MM-dd ..." based string into the "HH:mm ..." date. This will not work.
First convert your "yyyy-MM-dd" date string into a Date.
Then, format that Date into the String you need
String input = "2021-04-25T18:54:18";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH).parse(input);
String output = new SimpleDateFormat("HH:mm, yyyy-MM-dd", Locale.ENGLISH).format(date);
I'm trying to take two strings and make it into a Date object. I'm having trouble trying to work out what formats I need to use.
The first string is a date and is in the format of : 5th Jan
The second string is a time and is in the format of : 8:15
The main issue is what the format would be for the 5th
Since your date string, 5th Jan doesn't have a year, you will have to use some default year e.g. the current year, which you can get from LocalDate.now(). You can put defaults using DateTimeFormatterBuilder#parseDefaulting. Additionally, you can also make the parser
case-insensitive by using DateTimeFormatterBuilder#parseCaseInsensitive.
In order to parse a date string, 5th Jan, you can use the pattern, d'th' MMM. However, in order to deal with other suffixes like in 3rd, 1st etc., you should use the pattern, d['th']['st']['rd']['nd'] MMM where the patterns inside the square bracket are optional.
In order to parse a time string like 8:15, you can use the pattern, H:m.
Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
DateTimeFormatter dtfForDate = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseDefaulting(ChronoField.YEAR, date.getYear())
.appendPattern("d['th']['st']['rd']['nd'] MMM")
.toFormatter(Locale.ENGLISH);
DateTimeFormatter dtfForTime = DateTimeFormatter.ofPattern("H:m", Locale.ENGLISH);
String strDate = "5th Jan";
String strTime = "8:15";
LocalDateTime ldt = LocalDate.parse(strDate, dtfForDate)
.atTime(LocalTime.parse(strTime, dtfForTime));
// Print the default string value i.e. the value returned by ldt.toString()
System.out.println(ldt);
// The default format omits seconds and fraction of second if they are 0. In
// order to retain them in the output string, you can use DateTimeFormatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
String formatted = dtf.format(ldt);
System.out.println(formatted);
}
}
Output:
2021-01-05T08:15
2021-01-05T08:15:00
Learn about the modern date-time API from Trail: Date Time.
I'm trying to convert date string with 10 milliseconds (2018-11-02 6:05:59.1541162159 PM) to date but not able get the exact date.
Code to convert:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateFormatCheck {
private static TimeZone tz = TimeZone.getTimeZone("Asia/Colombo");
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS aa");
public static void main(String[] a){
try {
Calendar cal = Calendar.getInstance(tz);
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2018-11-02 6:05:59.1541162159 PM"));
Date date = cal.getTime();
System.out.println(date);
}catch (Exception e){
e.printStackTrace();
}
}
}
Output:
Tue Nov 20 02:12:01 IST 2018
There are multiple problems at the moment. I'd strongly recommend using java.time for as much work as possible, although even that doesn't make this easy.
As you say, your value has 10 digits for "fraction of a second" - which means it goes down to 10th-of-a-nanosecond precision. That's highly unusual to start with, in my experience - and I don't think Java can handle that, even with java.time.
I suspect you'll need to massage the data first, down to 9 digits of precision. At that point, it's fairly straightforward to parse the value to a ZonedDateTime:
// Note this only has 9 digits of precision, not the original 10
String text = "2018-11-02 6:05:59.154116215 PM";
ZoneId zone = ZoneId.of("Asia/Colombo");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd h:mm:ss.SSSSSSSSS a", Locale.US)
.withZone(zone);
ZonedDateTime parsed = ZonedDateTime.parse(text, formatter);
System.out.println(parsed);
Note how I've provided SSSSSSSSS as the fraction-of-a-second part, to handle all 9 digits. Also note the use of h instead of HH - HH would mean "24-hour hour of day, with 0 padding" - neither part of which is true for your original value, which uses "6" for 6pm. It's very rare that you would want to combine H or HH with a.
That code gives you a ZonedDateTime, which you could convert into a Date like this:
Date date = Date.from(parsed.toInstant());
I'd recommend you don't do that unless you really, really need to for interop reasons though; the Date API is nasty in various ways.
You need to format the date first with your SimpleDateFormat object:
System.out.println(sdf.format(date));
Edit: Do this once the parsing issue is resolved to print it out correctly.
String dateText = "2018-11-02 6:05:59.1541162159 PM";
String[] parsedText = dateText.split("\\.");
String[] parsedText2 = parsedText[1].split(" ");
String newText = new StringBuilder(parsedText[0]).append(" ").append(parsedText2[1]).toString();
ZoneId zone = ZoneId.of("Asia/Colombo");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm:ss a", Locale.US)
.withZone(zone);
ZonedDateTime parsed = ZonedDateTime.parse(newText, formatter).plusNanos(Long.parseLong(parsedText2[0]) / 10);
System.out.println(parsed);
You just need to read it with SimpleDateFormatter:
System.out.println(sdf.format(date.getTime()));
If you want read it with default date format:
private static String[] daysOfWeek = new String[]{"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
private static TimeZone tz = TimeZone.getTimeZone("Asia/Colombo");
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS aa");
public static void main(String[] a){
try {
Calendar cal = Calendar.getInstance(tz);
sdf.setCalendar(cal);
cal.set(Calendar.AM_PM, Calendar.PM);
cal.setTime(sdf.parse("2018-11-02 6:05:59.1541162159 PM"));
System.out.println(
daysOfWeek[cal.get(Calendar.DAY_OF_WEEK)] +
new SimpleDateFormat(" dd hh:mm:ss yyyy").format(cal.getTime()));
}catch (Exception e){
e.printStackTrace();
}
}
Good luck.