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() ;
Related
This question already has answers here:
What is this date format? 2011-08-12T20:17:46.384Z
(11 answers)
Closed 24 days ago.
Any help or hint would be greatly appreciated. From the below code I get this date:2023-01-25 16:30:22.998. How can I get this date: "FrmDt": "2023-01-16T23:59:59.938Z". It has a "T" which I not sure what this mean?
java.util.Date tsFrom = new java.util.Date();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(tsFrom);
calFrom.add(Calendar.YEAR, -1);
tsFrom.setTime(calFrom.getTime().getTime()); // or
sqlTSFromDate = new Timestamp(calFrom.getTime().getTime());
System.out.println("From date:" + sqlTSFromDate);
tl;dr
OffsetDateTime
.now( ZoneOffset.UTC )
.minus( Period.ofYears( 1 ) )
.toString()
2022-01-27T02:02:36.985475Z
ISO 8601
Study the ISO 8601 standard formats for textually representing date-time values.
Avoid legacy classes
Never use the legacy classes Date, Calendar, Timestamp. They are terribly flawed, designed by people who did not understand date-time handling.
java.time
Instead, use the java.time classes defined in JSR 310.
Apparently you want one year prior to the the current moment as seen in UTC.
Capture the current moment in UTC.
OffsetDateTime oneYearAgoInUtc = OffsetDateTime.now( ZoneOffset.UTC );
now.toString(): 2023-01-27T02:02:36.985475Z
Go back a year, using calendar dates as seen in the offset of zero, in UTC. First define the amount of time to go back, using Period for a scale of years-months-days.
Period p = Period.ofYears( 1 );
Then subtract.
OffsetDateTime then = now.minus( p );
then.toString(): 2022-01-27T02:02:36.985475Z
See that code run at Ideone.com.
To generate text in standard ISO 8601, merely call toString. The java.time classes use ISO 8601 formats by default when generating/parsing text.
String output = then.toString() ; // By default, standard ISO 8601 format.
2022-01-27T02:02:36.985475Z
The T separates the year-month-day portion from the hour-minute-second portion.
The Z indicates an offset from UTC of zero hours-minutes-seconds.
As several comments said, this is an ISO 8601 date.
In java, you can parse or write using SimpleDateFormat.
With the Z at the end, makle sure to use UTC/Zulu time.
Amending your code:
public static String ISO_8601 = "yyyyMMdd'T'HHmmss'Z'";
...
SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
sqlTSFromDate = dateFormat.format(tsFrom)
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 1 year ago.
Improve this question
how to convert ISO_LOCAL_DATE to date time format : yyyy-MM-dd'T'HH:mm:ss.SSSZ in java
Ex: given date: 2016-01-25 to 2016-01-25T00:00:00.000+0100
I am assuming that have got a string, for example 2016-01-25, and that you want a string containing the start of the day in the JVM’s default time zone (it wasn’t clear from the question). I first define a formatter for the format that you want (it’s ISO 8601):
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");
Now your conversion goes:
String isoLocalDateString = "2016-01-25";
LocalDate date = LocalDate.parse(isoLocalDateString);
ZonedDateTime dateTime = date.atStartOfDay(ZoneId.systemDefault());
String dateTimeString = dateTime.format(formatter);
System.out.println(dateTimeString);
When running in my time zone, Europe/Copenhagen, output from this example code is what you asked for:
2016-01-25T00:00:00.000+0100
In rare cases where summer time (DST) begins at the first moment of the day, the time of day will not be 00:00:00.000.
For parsing with ISO_LOCAL_DATE we don’t need to specify the formatter since this formatter is the default for LocalDate.parse().
All of this said, you should not normally want to convert a date from one string format to another string format. Inside your program keep dates as LocalDate objects. When you get string input, parse into a LocalDate. Only when you need to give string output, for example in data exchange with another system, format into a string in the required format.
Link: Wikipedia article: ISO 8601
There are various methods on LocalDate for this, including:
LocalDate::toDateTimeAtCurrentTime()
LocalDate::toDateTimeAtStartOfDay()
LocalDate::toDateTime( LocalTime )
LocalDate::toDateTime( LocalTime , DateTimeZone )
It is as simple as LocalDateTime localDateTime = yourLocalDate.atStartOfDay()
Update
Adding timestamp is as simple as:
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime = zdt = localDateTime.atZone(zoneId);
Can be put together as
ZonedDateTime zdt = yourLocalDate.atStartOfDay().atZone(ZoneId.of("America/New_York"));
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 1 year ago.
Improve this question
Requirement: Working on webinar meetings where a user can schedule a meeting by filling a form. The form contains a topic, description, list of members, meeting start time, and date. These details are stored in a table. After scheduling a meeting user can view his upcoming and previous meetings.
Dates are stored in this format 2021-02-22 using DATE datatype.
Start time: 12:48:00 in this format.
need to find whether the meeting date is yet commencing or it's a previous meeting?
public WebinarEntity getScheduledMeeting(int CompanyID){
Date currentDate=new Date(); //Todays Date.
//get the stored data.
DAO_Factory dao=new DAOImpl();
Date storedDate=dao.getMeetingDate(CompanyID);
if(currentDate.before(storedDate)
{
//display the meeting details as previous
}
else {
//display the meeting details as upcoming!
}
return new WebinarEntity(Details of previous or upcoming);
How to code to find the stored data is upcoming or previous based on Date and time?
Issue in above code: say for example our meeting scheduled on 22-2-2021 at 4:00 pm this meeting details are shown in the previous meeting column rather it should be shown/displayed in the upcoming.
EDIT: CurrentDate-2021-02-22 08:00am
Stored Date-2021-02-22 04:00pm
Never use either of the terrible Date classes. They were years ago supplanted by the modern java.time classes defined in JSR 310.
You tagged for the Joda-Time project. But you do not see to be using it. That project is now in maintenance mode, also supplanted by java.time.
Your Question ignores the crucial issue of time zone.
Book appointments using LocalDateTime and ZoneId, storing each of those in a pair of columns in your database. The SQL-standard types will be TIMESTAMP WITHOUT TIME ZONE and VARCHAR respectively. You may also want to store the duration of the meeting as text using standard ISO 8601 format.
At runtime, when you need to build out a schedule, combine the two to get a ZonedDateTime. This class represents a moment, and you can compare to the current moment to determine if it is past or future. To get the end of the meeting make a Duration object of your ISO 8601 string, and add to your ZonedDateTime start.
This has been addressed many many times already on Stack Overflow. I myself, and others, have written on this topic in much detail. So search to learn more.
CurrentDate-2021-02-22 08:00am
Stored Date-2021-02-22 04:00pm
LocalDateTime ldt = LocalDateTime.of( 2021 , 2 , 22 , 8 , 0 ) ; // Stored as TIMESTAMP WITHOUT TIME ZONE in database.
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // Stored as text in database, in `Continent/Region` format.
ZonedDateTime start = ldt.atZone( z ) ; // Dynamically calculated, not stored.
Duration duration = Duration.parse( "PT1H30M" ) ; // Stored in database as text, in standard ISO 8601 format `PnYnMnDTnHnMnS`.
ZonedDateTime end = start.plus( duration ) ; // Dynamically calculated, not stored.
ZonedDateTime now = ZonedDateTime.now( z ) ;
boolean isFuture = start.isAfter( now ) ;
Duration untilThen = Duration.between( now , start ) ;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a string date. Eg: "2020-02-21 16:36:30.072" and I want to convert it to Date "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". (i.e. 2020-02-21T16:36:30.072+05:30)
How? Could you please help me?
You need to start by converting the String into a more "malleable" format - something which can represent the date/time in a way through which you can generate different formats based on your need
Since it's 2020, you should start with the java.time.* API.
String input = "2020-02-21 16:36:30.072";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime ldt = LocalDateTime.parse(input, inputFormatter);
Ok, now, part of your requirement is to have the time zone, so you'll need to convert the LocalDateTime to a ZonedDateTime, you could, technically, do this in a single step, but it's a good demonstration
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
DateTimeFormatter outputFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
String output = outputFormatter.format(zdt);
System.out.println(input);
System.out.println(output);
This will output
2020-02-21 16:36:30.072
2020-02-21T16:36:30.072+11:00
I live in Australia, so my time zone is +10 (and +1 for daylight savings). You can specify a specific time zone if you wish, this is just for demonstration (and I couldn't be bothered trying to figure out 530+ time zone ;))
tl;dr
Here is a one-liner.
LocalDateTime
.parse(
"2020-02-21 16:36:30.072".replace( " " , "T" )
) // Returns a `LocalDateTime` object. *Not* a moment, *not* a point on the timeline. Just a date and a time-of-day, nothing more. Lacks context of a time zone or offset-from-UTC.
.atZone( // Lending context to our `LocalDateTime` object to determine a moment by assigning a time zone.
ZoneId.of( "Asia/Kolkata" ) // Currently using an offset of five and a half hours ahead of UTC.
) // Returns a `ZonedDateTime` object.
.format( // Generates text representing the value of the `ZonedDateTime` object.
DateTimeFormatter.ISO_OFFSET_DATE_TIME // Pre-defined formatter. No need to specify your own formatting pattern. Your desired format complies with the ISO 8601 standard.
) // Returns a `String`.
See this code run live at IdeOne.com.
2020-02-21T16:36:30.072+05:30
Details
The Answer by MadProgrammer is correct and nicely detailed. I will take some shortcuts, and address specifically your desired offset of +05:30.
We can parse your input as a LocalDateTime by merely replacing the SPACE character in the middle with an uppercase T.
String input = "2020-02-21 16:36:30.072".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime does not represent a moment, is not a point on the timeline. It lacks the context of a time zone or offset-from-UTC.
Your desired offset of +05:30 is currently used in only two time zones:
Asia/Colombo (Sri Lanka)
Asia/Kolkata (India)
Pick which one is yours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
Apply to your LocalDateTime to determine a moment, resulting in a ZonedDateTime.
ZonedDateTime zdt = ldt.atZone( z ) ;
Generate a String in standard ISO 8601 format extended wisely to append the name of the zone in square brackets.
String output = zdt.toString() ;
If you really want the offset only without the time zone, keep in mind that readers of your data won't know for sure if you meant Sri Lanka time or India time. If you insist, use the predefined DateTimeFormatter object as shown in the other Answer.
import java.util.Date;
public class Test {
public static void main(String[] args) {
String s0="2020-02-21 16:36:30.072";
Date date=new Date();
String sd=s0.split(" ")[0];
date.setDate(Integer.parseInt(sd.split("-")[2]));
date.setMonth(Integer.parseInt(sd.split("-")[1])-1);
date.setYear(Integer.parseInt(sd.split("-")[0])-1900);
String st=s0.split(" ")[1];
date.setSeconds((int) Double.parseDouble(st.split(":")[2]));
date.setMinutes(Integer.parseInt(st.split(":")[1]));
date.setHours(Integer.parseInt(st.split(":")[0]));
System.out.print(date);
}
}
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.