Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I just started taking a computer science class a week ago, and I found this code to get the date and time. But I don't fully understand what everything in this means. If anyone could clarify that would be awesome! :)
long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.print("Date: ");
System.out.println(sdf.format(resultdate));
long yourmilliseconds = System.currentTimeMillis();
get the number of milliseconds from the System
Date resultdate = new Date(yourmilliseconds);
Creates a date from it. These two lines could be changed to
Date resultdate = new Date();
As dates in JDK1.7 and previous did not have any intrinsic formatting a formatting class is used
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
This is the pattern it will print as
System.out.println(sdf.format(resultdate));
Now we call the formatting method and print it out.
Scary Wombat did a good job explaining the individual steps to you, but there is a bit more to it.
First of all, learning programming is about making experiences yourself. So, your first step to approach this would be: take that source code, and instead of pasting it into a SO question ... paste it into a "public static void main" method; within a public class; compile it, run it, and see what happens. And start playing around with it.
If that leaves you with questions, the next step would be to lookup javadoc - you see; all your code deals with standard classes; and they are all well documented.
So, lesson for today: asking here is OK, but make sure that you really try to figure such things yourself first! Not only because the policy of this site says so, but because that gives you the most learning results out of your efforts!
java.time
That code:
Captures the current moment (date-time)
Generates a String to textually represent that moment.
Note that these are two distinct concepts. A date-time object is not a String. A date-time object generates a String to represent its value. Novice programmers often conflate the two causing much confusion and frustration.
Unfortunately that code snippet uses some old legacy date-time classes now supplanted by the java.time classes. The old classes have proven to be poorly designed, confusing, and troublesome.
The modern way to capture the current moment is simple. The Instant class represents a moment in the timeline in UTC with a resolution up to nanoseconds.
Instant instant = Instant.now();
To generate a String that represents that moment in standard ISO 8601 format, simply call toString.
String output = instant.toString();
2016-09-12T05:36:55Z
Adjust into a particular time zone (ZoneId) to see the same moment through the lens of that region’s wall-clock time.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Again, to generate a String that represents that moment in standard ISO 8601 format, simply call toString. Actually, the ZonedDateTime extends the standard by wisely appending the name of the time zone in square brackets.
String output = zdt.toString();
2016-09-12T01:36:55-04:00[America/Montreal]
To generate Strings in other formats, search Stack Overflow for the java.time class DateTimeFormatter.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
Does anyone know how to grab or create the cdate value from Date? I haven't been able to figure out how to do so and I don't know how to necessarily get it. In the Date class it is there as
private transient BaseCalendar.Date cdate; I don't see an option to grabt the field from the Date object itself.
I am setting this date using request.setGatewayEndTime(Calendar.getInstance().getTime());
where the calendar is from the java.util.Calendar import
debug pic
As commented, trying to access internally defined fields that were intentionally hidden from outside calling programmers would be unwise.
As commented, you seem to have an XY Problem. I'll take a stab at what you might need.
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Calendar, Date, etc.
You claim to have a call to a method requiring a java.util.Date object that represents the current moment as seen in UTC, that is, with an offset of zero hours-minutes-seconds. To capture the current moment, use Instant class.
Instant now = Instant.now() ; // Current moment as seen with an offset of zero.
I suggest you educate the author of that called method about how Date has been replaced by Instant.
Until they update their API, you can easily convert between legacy and modern classes by calling conversion methods added to the old classes.
java.util.Date d = Date.from( now ) ;
request.setGatewayEndTime( d );
As for the BaseCalendar.Date field, if your goal is to get a string in ISO 8601 format similar to the string you show in your screenshot which is nearly in standard format but omits the COLON from between the hours and minutes of the offset, then simply call Instant#toSting. The java.time classes use ISO 8601 format by default when parsing/generating strings.
String output = now.toString() ; // Generate text in standard ISO 8601 format.
Your screenshot uses another offset other than zero. If you wish to see a moment with the offset of a particular time zone, apply a ZoneID object to produce a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/La_Paz" ) ;
ZonedDateTime zdt = now.atZone( z ) ;
Produce text in standard ISO 8601 format that has been wisely extended to include the name of the time zone in square brackets.
String output = zdt.toString() ;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I work with the date in my API on Java. I want to get today's date and time, write it to a class and then to a csv file (I use a csv file as a data store). Then, to implement the function of getting a report on records for today, to get it and to compare it with today's date (exactly the date, without time). What is the best way to do this? Right now I'm storing this in Timestamp, but it doesn't seem to be correct and should I use String? Then I need two parsers? To translate from a string to a date and time and from that to just a DATE? Which library is better to use for this?
I wrote a translation from a string to a timestamp, is this correct?
default Timestamp StringToTimestamp(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
log.error("Error in date parsing");
}
return new Timestamp(parsedDate.getTime());
}
UPD
I changed my code for the java.time library, but it seems I did something wrong
default LocalDate StringToTimestamp(String date) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern('yyyy-mm-dd');
LocalDate date = LocalDate.parse(date, dtf);
return date;
}
UPD I edited the code according to the answer #OleV.V. It works really cool
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. I suggest writing the current date and time with offset from UTC to the CSV file.
OffsetDateTime dateTime = OffsetDateTime.now(ZoneId.systemDefault());
String stringForCsvFile = dateTime.toString();
System.out.println(stringForCsvFile);
Output when running in my time zone just now:
2020-12-26T11:02:07.368973+01:00
The string is in ISO 8601 format, which should be the best to avoid surprises for anyone reading it. The classes of java.time generally print ISO 8601 format from their toString methods.
Often you will value consistency higher than knowing which UTC offset was used when writing the file. If so, write the time in UTC to the file:
Instant now = Instant.now();
String stringForCsvFile = now.toString();
2020-12-26T10:02:07.373439Z
No matter which way you used above, after reading the timestamp from the file, convert like this:
ZoneId zone = ZoneId.systemDefault();
String stringFromCsvFile = "2020-12-26T11:02:07.368973+01:00";
ZonedDateTime dateTime = OffsetDateTime.parse(stringFromCsvFile)
.atZoneSameInstant(zone);
LocalDate dateFromCsv = dateTime.toLocalDate();
LocalDate today = LocalDate.now(zone);
System.out.println("Same day? " + dateFromCsv.isEqual(today));
Same day? true
I have made sure that both dates I compare are in the time zone of the JVM where the program is running. Please consider whether there’s a specific time zone you want, and if so, set zone to something like ZoneId.of("Asia/Baku"). It matters: it is never the same date in all time zones.
If you want to know whether the date is earlier or later, use the isBefore or isAfter method of LocalDate.
Was your code correct?
IMHO the worst problem with your code is using the old and poorly designed date-time classes: SimpleDateFormat, Date and Timestamp. SimpleDateFormat is a notorious troublemaker of a class. Date had severe design flaws in Java 1.0, therefore most constructors and methods were deprecated already in Java 1.1. Timestamp was never meant for other purposes than transferring high-precision timestamps to and from SQL databases (which we also don’t use it for anymore). And it’s a true hack on top of the already poorly designed Date class. I furthermore see nothing that you will want to use the high precision of Timestamp for, so using it here seems pointless.
There is a bug in your code: You are using upper case YYYY in your format pattern. This is for week year and only useful with a week number. I tried giving 24-06-2021 to your method. It returned 2021-01-04 00:00:00.0. It’s 5 months 20 days off because of the mentioned error. Apparently SimpleDateFormat defaulted to the start of week 1 in the week year and ignored the month and day of month.
As an aside, had you tried parsing with the same format pattern string with java.time, it would at least have told you that this was wrong.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Related question: java parsing string to date
This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Closed 4 years ago.
I am trying to convert a java.util.Date to XMLGregorianCalendar in Italian format (dd/mm/yyyy) with no time. Whatever I try the output always prints yyyy-mm-dd.
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Rome"));
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH),
DatatypeConstants.FIELD_UNDEFINED);
System.out.println(xmlDate);
I am a consumer of SOAP web-service, and the date attribute is defined as XMLGregorianCalendar.
Please advise how can I change the code to get the output with format (dd/mm/yyyy).
You don’t need an XMLGregorianCalender. It will not, cannot give you what you ask for. Instead you need a LocalDate and a DateTimeFormatter:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.ITALIAN);
LocalDate date = LocalDate.now(ZoneId.of("Europe/Rome"));
String formattedDate = date.format(italianDateFormatter);
System.out.println(formattedDate);
When I ran this code today, the output was:
21/01/19
The difference from what you ask for is the two digit year, 19. If instead of FormatStyle.SHORT we use FormatStyle.MEDIUM, we get four digit year, but the month as a three letter abbreviaiton:
21-gen-2019
The advantage is that the code lends itself very well to internationalization: you just need to change the locale to get proper code for some other language and country. If you do need 21/01/2019 (with four digit year), specify the format explicitly using a pattern:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofPattern("dd/MM/uuuu");
21/01/2019
What’s wrong with using XMLGregorianCalendar?
When you call System.out.println(xmlDate), you are implicitly calling toString on your XMLGregorianCalendar. When it hasn’t got time and zone offset, toString always generates yyyy-MM-dd format, there is no way you can change that. On the other hand you can have any format you like in a String. Next obstacle is, there is no formatter that can format an XMLGregorianCalendar directly. You would need to convert to a different type, like ZonedDateTime, for example, first. Since you only want the date, neither the time of day nor the time zone, it’s simpler and easier to start out from LocalDate from the start. Not least for those reading and maintaining your code after you.
Your question mentions java.util.Date and your code uses GregorianCalendar too. Both of those classes are poorly designed and long outdated, fully replaced by java.time, the modern Java date and time API. So I suggest you don’t use them.
Link
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm a bit baffled what format these timestamps are in. I was told the format to use is yyyy-MM-dd.HH:mm:ss but all of the timestamps appear like this 2017-01-01 00:08:57.231, 2017-01-01 07:43:36.348, or 2017-01-01 13:25:55.683. I'm not understanding why there are four sections to the time ?:Hour:Minute:Second in the actual data I have when the format I'm supposed to be using only has three time sections. Are these datetime timestamps not actually in the format of yyyy-MM-dd.HH:mm:ss?
No, your suspicion is correct, your example date-time strings are not in the format yyyy-MM-dd.HH:mm:ss. The dot between dd and HH must be a simple mistake, it should be a space since there is a space between date and time in the timestamp strings. Furthermore all of your example strings include milliseconds: in 00:08:57.231 you’ve got 57 seconds and 231 milliseconds, or if you like, 57.231 seconds, so the last section may also be referred to as fraction of second.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String timestampString = "2017-01-01 00:08:57.231";
LocalDateTime dateTime = LocalDateTime.parse(timestampString, formatter);
System.out.println(dateTime);
Output:
2017-01-01T00:08:57.231
For the nerdily curious: It is possible to parse the string, or more precisely most of it, with the format you had been given, only correcting the dot into a space:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestampString = "2017-01-01 00:08:57.231";
LocalDateTime dateTime = LocalDateTime.from(
formatter.parse(timestampString, new ParsePosition(0)));
In this case the result comes without the milliseconds:
2017-01-01T00:08:57
I see no reason why you should want this, though.
Avoid SimpleDateFormat
In a comment you gave a snippet that uses the SimpleDateFormat class. This class is not only long outdated, it is also notoriously troublesome. I see no reason why you should want to use it. Instead I am using java.time, the modern Java date and time API. In my experience it is so much nicer to work with.
Links
Oracle tutorial: Date Time explaining how to use java.time. You may especially want to study the section Parsing and Formatting.
These time stamps are in yyyy-MM-dd HH:mm:ss:ms format, last three digits are milliseconds.
Appreciate there are lots of similar posts on this but I couldn't find a specific one to help.
I'm trying to convert this string to a Date in Java
2017-05-16 06:24:36-0700
But it fails each time with this code
Date Login = new SimpleDateFormat("dd/MM/yy HH:mm:ss").parse("2017-05-16 06:24:36-0700");
Now I'm presuming its due to the timezone info at the end - I just can't figure out how to set the format. I tried this but no luck
SimpleDateFormat("dd/MM/yy HH:mm:ssZ")
Any ideas?
The date format passed to your SimpleDateFormat is "dd/MM/yy", while the date you are trying to parse is of the format "yyyy-MM-dd". Try this instead:
Date login = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse("2017-05-16 06:24:36-0700");
As a side note, depending on which version of Java you are using, I would recommend using the new java.time package (JDK 1.8+) or the back port of that package (JDK 1.6+) instead of the outdated (no pun intended) Date and/or Calendar classes.
Instant login = Instant.from(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ").parse("2017-05-16 06:24:36-0700"));
I have already upvoted Bryan’s answer exactly because it includes and recommends the java.time solution. I need to add a few thoughts, though.
Your code, reviloSlater, throws away the time zone information (more precsely, zone offset information), I’m not sure I would dare do that from the outset. With java.time classes it’s more natural to include it, and it’s easy to discard at a later point when we are sure we don’t need it.
To parse with offset:
OffsetDateTime loginOdt = OffsetDateTime.parse("2017-05-16 06:24:36-0700",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ"));
To drop the time zone offset information
LocalDateTime loginLdt = loginOdt.toLocalDateTime();
A LocalDateTime is a date and a time without any time zone or offset information. In this case of course we get
2017-05-16T06:24:36
Bryan’s java.time code too uses the time zone offset information from the string. Edit: after Bryan’s edit that code now works and gives us:
2017-05-16T13:24:36Z
This is the same point in time (Instant.toString() prints the time in UTC). Another way is, with the OffsetDateTime from before we can just do
Instant login = loginOdt.toInstant();
java.time is loaded with possibilities.