I need to retrieve day year and month from a timestamp object as long numbers:
public long getTimeStampDay() { String iDate = new SimpleDateFormat("dd/MM/yyyy") .format(new Date(born_date.getDate())); ..... return day; //just the day } public long getTimeStampMonth() { String iDate = new SimpleDateFormat("dd/MM/yyyy") .format(new Date(born_date.getDate())); ..... return month; //just month } public long getTimeStampYear() { String iDate = new SimpleDateFormat("dd/MM/yyyy") .format(new Date(born_date.getDate())); ..... return year; //just year }
born_date
is a timestamp object.
Is it possible to do that?
Thanks in advance.
You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.
Use the MONTH() function to retrieve a month from a date/datetime/timestamp column in MySQL. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a date/datetime/timestamp column. (In our example, we use the start_date column of date data type).
Getting the Current Time Stamp If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method. const currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.
We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
long timestamp = bornDate.getTime(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timestamp); return cal.get(Calendar.YEAR);
There are calendar fields for each property you need.
Alternatively you can use joda-time:
DateTime dateTime = new DateTime(bornDate.getDate()); return datetime.getYear();
A little refreshment of this well-accepted thread that is a bit outdated by now.
Back in the day, Java 8 introduced Date and Time API which makes extracting much cleaner.
Let's assume that bornDate
is instance of LocalDateTime
.
bornDate.getDayOfMonth(); // extracts day of month bornDate.getMonth(); // extracts month bornDate.getYear(); // extracts year
Oracle reference: Java SE 8 Date and Time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With