How to get epoch milis from a date (LocalDate) - android

I have a month July 2022 for example, I want get epoch milis for the first day of the month
1st July 2022 at midnight.
from the month I was able to get the 1st July 2022, but how to convert it into epoch milis for 1st July 22 midnight
val datey = "July/2020"
val dateFormaty = DateTimeFormatter.ofPattern("MMMM/yyyy")
val yearMonthy = YearMonth.parse(datey, dateFormaty)
val parsedDatey = yearMonthy.atDay(1)
I get 2022-07-01 for parsedDate, I want to get the date time for this date in epoch milis
Thanks
R

Like I mentioned, LocalDate does not actually store any time information whatsoever, so transforming it to epoch isn't possible. Technically. Yet it is with some possible inacuracies.
How about something like this:
make the following extension function
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
Note that it uses the system default timezone for this, to provide the necessary information.
then just use it.
val myDate = myLocalDate.toDate()
which would in your case, be parsedDatey.toDate()
But, we don't really even need the Date here. Lets avoid casting the LocalDate to Date then getting the epoch milli from there, and just do it from the provided Instant instead.
So the real answer to your question is this:
fun LocalDate.getEpochMillis(): long = this.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
// call this in your parsing method you posted
parsedDatey.getEpochMillis()

Related

Conversion of date and time to unix timestamp - kotlin

In timestamp variable, I want to get the timestampt value with the current hour, minute and second. The currentDataTime gives me the time in this format: 2020-08-28 17:18:02.
Currently, the timestamp variable returns me 1598645882634 (the last 3 numbers are the miliseconds) but when I convert it in a online conversor to a Human readable format, it gives me 08/28/2020 # 8:18pm (UTC). The only one problem is the hour and minute tha is 3 hours different because of my zone. How can I convert the date AND time to timestamp?
object DateTime {
val currentDataTime: String
#SuppressLint("SimpleDateFormat")
get() {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
return dateFormat.format(Date())
}
val timestamp: String
get(){
val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date = formatter.parse(currentDataTime) as Date
return date.time.toString().dropLast(3) //it is returning
}
}
A Unix timestamp is defined to be (almost) UTC. It carries no timezone information so it cannot be shifted according to a timezone difference without everything based on it falling apart. (If you'd like to hardwire it anyway, according to your example just add your timezone difference in milliseconds. But read on first.)
Localized time can only be interpreted consistently as long as the proper timezone is attached. It jumps back and forth whenever daylight-savings time starts or ends. If that's not complicated enough, the rules for daylight-savings time may change at any time (and do so around the globe).
Your online converter apparently just took a UTC-based timestamp and displayed it according to your local timezone.
To handle localized date and time values, use the multiplatform date/time library kotlinx-datetime. In the README section Converting an instant to local date and time components you'll find this example:
val currentMoment: Instant = Clock.System.now()
val datetimeInUtc: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.UTC)
val datetimeInSystemZone: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.currentSystemDefault())
There you'll also find elaborate explanations on which type of date and time to use in which scenario.

Difference between 2 dates in days and in double

I am working on an app and i need to get the difference between the actual date and a date inserted by the user, in days and in double.
Any idea on how to make this? I've tried some things but without success.
First you must decide if you want to consider the time of the day and the timezone to calculate the difference, because this can lead to different results.
Example: current date (AKA "today") is April 17th or 18th, depending on where in the world you are. Actually, depending on the time of the day, there might be 3 different "todays" in the world, at the same time. What timezone are you using to calculate the difference?
the user will enter a date: only day, month and year? Will it enter the hours? Are you using the user's device's timezone or some specific zone?
the same questions apply to the current date
Depending on the choices you make, you might get a different result.
Anyway, I'd use this lib: http://www.threeten.org/threetenbp/
or java.time classes, if available in your API level. In both API's you can use the following.
To use a date (day-month-year only) and the device's default timezone, I'd choose the LocalDate class:
// current date in device's default timezone
LocalDate now = LocalDate.now();
// some date from input values (May 10th 2018)
LocalDate dt = LocalDate.of(2018, 5, 10);
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
If you want to consider the time of the day (hours, minutes, etc), use a LocalDateTime. But in this case, ChronoUnit.DAYS considers a day has passed when the time is >= the other (ex: the difference between April 17th at 10 AM and April 18th 9:59 AM is zero days, because the time of the day didn't reach 10 AM, so it didn't complete 1 day - with LocalDate this doesn't happen because this class doesn't have time-of-the-day fields and considers only the day, month and year).
If you want to consider everything (date, time, and timezone), including Daylight Saving Time transitions, use a ZonedDateTime instead (the code is very similar, the only difference is that you can choose a timezone to work with):
// current date/time in device's default timezone
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// some date from input values (May 10th 2018, 10 AM in New York timezone)
ZonedDateTime dt = ZonedDateTime.of(2018, 5, 10, 10, 0, 0, 0, ZoneId.of("America/New_York"));
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
You can choose between the device's default timezone (ZoneId.systemDefault()) or a specific one (ZoneId.of("America/New_York")). You can check all the available timezones with ZoneId.getAvailableZoneIds().
Maybe it doesn't make sense to use current date in one timezone and user's date in another (I'd use the same for both), but that's up to you to decide.
Calendar c = Calendar.getInstance();
Calendar c2 // = what you will get from the user
long diff = c.getTimeInMillis()-c2.
double days = (double) diff/(1000*60*60*24);
that is what i have in mind.
I hope this helps
use this way
public static double getTimeDiffBetweenDate(Date startDateTime, Date finishDateTime) {
long diffInMilliseconds = finishDateTime.getTime() - startDateTime.getTime();
return TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds) / 60.0;
}

LocalDateTime and DateTimeZone.getDefault returning UTC time

I am trying to set the date time of a local object. Here is my code:
val date = DateTime() //returns UTC time
val dateTimeZone = DateTimeZone.getDefault() //returns UTC
val localDateTime = LocalDateTime() //returns UTC
My phone settings are set to automatic date time, and my current time zone is Mountain Time.
How can I get the current time in my time zone (the one appearing on my phone)?
If DateTimeZone.getDefault() returns "UTC", that's because the device's default timezone is set to it, so all classes will refer to it unless you specify another zone.
To get the date and time at a specific timezone, you can do:
val date = DateTime(DateTimeZone.forID("America/Denver"))
val localDateTime = LocalDateTime(DateTimeZone.forID("America/Denver"))
Note that America/Denver is just one of the many regions that uses Mountain Time. That's because Joda-Time uses IANA zones names (in the format region/city), so you must choose the best one accordingly from this list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Optionally, you can also change the default timezone:
DateTimeZone.setDefault(DateTimeZone.forID("America/Denver"))
With this, just calling LocalDateTime() or DateTime() will use America/Denver as the default zone.
But remind that this will change the default timezone for the whole JVM, so think if that's what you need before doing so.

Converting milliseconds to Date object

I am having following code to convert milliseconds to Android Date object.
Date dateObj = new Date(milli);
But problem is that my milliseconds value is having GMT value added in it before i pass it to Date class, add when i print this date object i can see that date object is again adding GMT value in the milliseconds value and because of that my date is displayed as wrong.
So how can i generate Date object with out considering GMT value in it.
For example my milliseconds are 1385569800000 which is getting printed as below:
Wed, 27 Nov 2013 22:00:00 --> +5.30
But the current value of this time stamp without adding GMT is:
Wed, 27 Nov 2013 16:30:00
*UPDAE*
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
So basically i want to create Date object which has proper date time value in it with out adding extra GMT time added in it.
A Date is always in UTC. No need to change that.
When printing the date value, use SimpleDateFormat and call setTimeZone() on it before formatting the output string.
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
TimerTask is just a task and not its scheduling. Timer accepts a Date object for scheduling. The Date is in UTC there as well.
try my code if you a
long currentTime = System.currentTimeMillis();
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
currentTime -= offsetInMillis;
Date date = new Date(currentTime);
it is work for me
You can try with joda-time API.
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.
http://joda-time.sourceforge.net/key_instant.html
A Date object simply represents a moment in time. Imagine you're on the phone to someone on a different continent, and you say "3...2...1...NOW!". That "NOW" is the same moment for both of you, even though for one person it's 9am and for the other it's 4pm.
You're creating a Date representing the moment 1385569800000 milliseconds after the Java epoch (the beginning of 1970, GMT). That is your "NOW", and it's fixed and unchanging. What it looks like converted into text, however, depends on which timezone you want to display it for. Java defaults to using GMT, which would be right if you were in Britain during the winter, but for (I'm guessing) India you want it in a different time zone. Laalto's answer shows you how to do that.
here is the code,that worked like charm for me:
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

Using System.currentTimeMillis() to get time on emulator

I've being using System.currentTimeMillis() to get the current time of an action occuring in my Android activity. The time it gives when converted to a date something like this Thu 20 January 1970 20:15. I am wondering if this is just because I am using it on the emulator of is there something gone wrong?
EDIT:
times = System.currentTimeMillis();
//Converting to Date using constructor Date(long milliseconds)
Date changeToDate = new Date(times);
It's just a guess: you probably convert millis to date incorrectly. Don't you divide them by 1000 while passing to Date constructor?
which Date class did you import in your project? probably you have imported java.sql.Date but the one which you should use is java.util.Date - perhaps this helps a little bit.. #a.ch. : java.util.Date needs milliseconds, not seconds (ms/1000) in its constructor ;)

Categories

Resources