I am using below function to take the today's date :
fun getCurrentDateTime(dateFormat: String): String {
val Datetime: String
val c = Calendar.getInstance()
val dateformat = SimpleDateFormat(dateFormat, Locale.getDefault())
Datetime = dateformat.format(c.time)
return Datetime
}
I have filter for today to sort fetch today's filtered data. But, With the above function I am filtering with the same values,
Means start date for Today and end date for Today are both same.
I want it different.
Means :
Start Date should be 1639560609 (Wednesday, 15 December 2021 00:00:00 GMT+05:30)
and
End Date should be Current time (which I am getting with above function)
So, The Issue you got that I want the Today's start Date with start time of the day.
How ? Thanks.
Use LocalDateTime to get current date and start of the day
val dateFormatter = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy HH:mm:ss")
val localDate = LocalDate.now() // your current date time
val startOfDay: LocalDateTime = localDate.atStartOfDay() // date time at start of the date
val timestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() // start time to timestamp
Log.d("Date:", "start date $timestamp")
Log.d("Date:", "start date parsed ${startOfDay.format(dateFormatter)}")
Output:
Start Date Timestamp : 1639506600000
Parsed TimeStamp: Wednesday, 15 December 2021 00:00:00
Edit : To get end of date time
val endOfDate: LocalDateTime = localDate.atTime(LocalTime.MAX)
val timestampEnd = endOfDate.atZone(ZoneId.of("UTC")).toInstant().epochSecond
Capture the current moment.
Instant now = Instant.now() ;
Understand that, for any given moment, the date varies around the globe by time zone. At one moment, it can be “tomorrow” in Tokyo Japan 🇯🇵 while simultaneously “yesterday” in Edmonton Alberta Canada 🇨🇦.
Specific time zone
Get the date in effect at that moment in a specific time zone. Here we use the time zone of India 🇮🇳.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
LocalDate todayKolkata = now.atZone( zKolkata ).toLocalDate() ;
Get the first moment of the date in that zone.
ZonedDateTime startOfTodayKolkata = todayKolkata.atStartOfDay( zKolkata ) ;
Get the count of whole seconds from first moment of 1970 UTC to that first moment of that date in Kolkata.
long secondsSinceEpochToStartOfTodayKolkata = startOfTodayKolkata.toInstant().getEpochSecond() ;
If you want to track the full length of the day, use Half-Open approach. In Half-Open, the beginning is inclusive while the ending is exclusive. So a full day starts at the first moment of one date and runs up to, but does not include, the beginning of the following day.
ZonedDateTime startOfTomorrowKolkata = todayKolkata.plusDays( 1 ).atStartOfDay( z ) ;
Track the full day as a pair of Instant objects, using the Interval class from the ThreeTen-Extra library.
Interval allDayTodayKolkata = Interval.between( startOfTodayKolkata , startOfTomorrowKolkata ) ;
UTC (offset of zero)
In contrast, determine the first moment of today’s date as experienced with an offset of zero hours-minutes-seconds.
LocalDate todayUtc = now.atOffset( ZoneOffset.UTC ).toLocalDate() ;
ZonedDateTime startOfDayUtc = todayUtc.atStartOfDay( ZoneOffset.UTC ) ;
long secondsSinceEpochToStartOfDayUtc = startOfDayUtc.toInstant().getEpochSecond() ;
Here is how can you can get the number of hours later time from current time in Kotlin:
https://stackoverflow.com/a/73050414/7126848
Related
I have a simple code where i want to convert a certain given time to another time zone , in my case the time is local to UK , but i need to convert the time to another timezone if the user lives in different country , i have tried this simple code but it is not working for me , it is giving me random hour 04:00
any help would be appreciated guys
This is the code
var localTime = "16:00" // simulating time to Uk timezone
localtime.text = localTime
timeZone.setOnClickListener {
val localTimes = "16:00"
val timeFormatter = SimpleDateFormat("hh:mm", Locale.UK)
val timezone = TimeZone.getDefault() // get device timezone
timeFormatter.timeZone = timezone
val timeToFormat = timeFormatter.parse(localTimes)
val formattedTime = timeFormatter.format(timeToFormat)
localtime.text = formattedTime
}
I'm trying to convert this time stamp value to date but its giving me wrong time. date is correct
TimeStamp : 1423821615
True Value : Fri, 13 Feb 2015 10:00:15 GMT
Android Code shows : Fri, 13 Feb 2015 15:30:15 IST
Here is the code I'm using to convert time stamp to date.
Date dt = new Date((long)timestampInSeconds * 1000);
I tried this code too but same result
public static Date getDateFromTimeStamp(long timestampInMilliseconds) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestampInMilliseconds);
return cal.getTime();
}
Date dt = getDateFromTimeStamp((long)timestampInSeconds * 1000);
I don't know what I'm doing wrong. Please help
Now I explain the whole scenario. My client is from UK and I'm from India (+5:30 ahead). He created appointment for 10 AM in UK obviously. But now I have his database in my local PC. My .NET software it shows same time as it shows in below image of SQL server. But in mobile, it doesn't. PC and mobile both are in same time zone.
I use this code to convert date to time stamp and send this time stamp to mobile app through web service
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, Appointments.DateTime) AS AppointmentTimeStamp FROM Appointments
Here is image of what my .NET software displays
does it matter that record was created when database was in UK time zone. Or I'm still doing a mistake somewhere.
I didn't understand what you wanna get.
If you get time as EPOCH time, you don't have information about time zone where this time stamp was made. So, you should know time zone offset and + or minus this seconds from this time stamp.
But I think the best way to use ISO 8601 format for time stamp, it's easy to convert to any timezone what you need
for example, this code convert ISO data to local time or return current time depends on locale timezone
private long time2LocalTimeZone (String date){
//"2016-07-29T23:07:45.120+00"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
try {
return sdf.parse(date).getTime();
} catch (ParseException e){
return (new Date()).getTime();
}
}
this code count your offset from GMT timezone and convert to epoch time depends on locale timezone
private long time2LocalTimeZone (long date){
TimeZone tz = TimeZone.getDefault();
Date now = new Date();
int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
return date + offsetFromUtc;
}
I am trying to convert ISO 8601 time into something human readable and in the local timezone of the Android device.
String date = "2016-09-24T06:24:01Z";
LocalDate test = LocalDate.parse(date, ISO_INSTANT);
But it returns:
method threw 'org.threeten.bp.format.DateTimeParseException' exception
From reading http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/DateTimeFormatter.html#ISO_INSTANT it seems like what I'm doing should be possible.
What am I doing wrong?
Edit
Expanded exception error:
Unable to obtain LocalDate from TemporalAccessor: DateTimeBuilder[fields={MilliOfSecond=0, NanoOfSecond=0, InstantSeconds=1474698241, MicroOfSecond=0}, ISO, null, null, null], type org.threeten.bp.format.DateTimeBuilder
Edit 2
The solution is in the answer below. For anyone that stumbles across this, if you want to specify a custom output format you can use:
String format = "MMMM dd, yyyy \'at\' HH:mm a";
String dateString = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()).format(instant);
#alex answer is correct. Here is a working example.
Instant represents a point in time. To convert to any other local types you will need timezone.
String date = "2016-09-24T06:24:01Z";
This date string is parsed using the DateTimeFormatter#ISO_INSTANT internally.
Instant instant = Instant.parse(date);
From here you can convert to other local types just using timezone ( defaulting to system time zone )
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
LocalTime localTime = instant.atZone(ZoneId.systemDefault()).toLocalTime();
Alternatively, you can use static method to get to local date time and then to local date and time.
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
You need to use Instant.parse().
This will give you an Instant that you can combine with a time zone to create a LocalDate.
In Kotlin:
Converts to LocalDateTime directly based on your local time zone::
val instant: Instant = Instant.parse("2020-04-21T02:22:04Z")
val localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime()
Converts to Date and time separately based on your local time zone:
val localDate: LocalDate = instant.atZone(ZoneId.systemDefault()).toLocalDate()
val localTime: LocalTime = instant.atZone(ZoneId.systemDefault()).toLocalTime()
I am building a basic logging utility class and would like to log the date and time down to the millisecond of when the log entry is created. I'm currently using:
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d )
which gives me '05-23 09:05:47'. I would like it to give me the milliseconds of when the log entry is created also and it does not appear that the DateFormat class supports millisecond retrieval.
Like the format "MM-dd hh:mm:ss:zzz" giving '05-23 09:05:47.447'.
Is it possible to do this using the DateFormat class (or a class like DateFormat)? I recognize it is possible to create another date removing the milliseconds part of this date and then subtracting the two and printing the difference but that's just silly. (:
Try this
Date d = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd hh:mm:ss SSS");
String dateToOutput = sdf.format(d);
While I think it's silly the DateFormat class doesn't allow easy formatted output of milliseconds, I realized that obtaining the milliseconds from the timestamp is actually quite easy. Every date object is representing a timestamp in milliseconds since 00:00 January 1, 1970 so the timestamp modulo 1000 gives the milliseconds.
I did
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d );
dateToOutput += "." + d.getTime() % 1000;
which, while not ideal, works fine and gives me '05-23 09:05:47.447'.
In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();
you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.
Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}