In Xamarin.Android, you work with both .NET and Java.
I get a return value of Java.Util.Date, I then need to input that same value as a parameter that only takes System.DateTime
This is how I currently do it
public static DateTime ConvertJavaDateToDateTime(Date date)
{
var a = date.ToGMTString();
var b = date.ToLocaleString();
var c = date.ToString();
DateTime datetime = DateTime.ParseExact(date.ToGMTString(), "dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);
return datetime;
}
However on the first 9 days of any month, I only get 1 digit for the day, and the
DateTime.ParseExact function is looking for dd (i.e. 2 digits for the day).
a is a string with value "1 Sep 2014 14:32:25 GMT"
b is a string with value "1 Sep 2014 16:32:25"
c is a string with value "Mon Sep 01 16:32:25 EET 2014"
I wish I could find a simple, quick, reliable and consistent solution for this problem :D
java.util.Date has a getTime() method, which returns the date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
With that knowledge, you can construct a System.DateTime, that matches this value like so:
public DateTime FromUnixTime(long unixTimeMillis)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTimeMillis);
}
(method taken from this answer)
Do this:
public DateTime ConvertDateToDateTime(Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
String dateFormated = dateFormat.format(date);
return new DateTime(dateFormated);
}
I'll update my answer, since you've changed the question.
you can use a long to hold the milliseconds and than convert the milliseconds to ticks(x10000) and create a new DateTime
Date date = new Date();
Long milliseconds = date.getTime();
Long ticks = milliseconds * 10000
DateTime datetime = DateTime(ticks);
I had this problem when authenticating with Facebook to receive the Expire time for the token. The solution was to do this:
var convertedTime = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddMilliseconds(MyJavaUtil.Date.Time);
I used this:
DateTimeOffset.FromUnixTimeMilliseconds(date.Time - (date.TimezoneOffset * 60 * 1000)).DateTime;
To incorporate the timezone offset into my date.
In my case, only this code works correctly:
public static DateTime NativeDateToDateTime(Java.Util.Date date)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
string dateFormated = dateFormat.Format(date);
return DateTimeOffset.Parse(dateFormated, null, DateTimeStyles.None).DateTime;
}
It is not tested but try with Calendar methods
public static String ConvertJavaDateToDateTime(Date date)
{
Calendar c = new GregorianCalendar();
c.setTime(date);
System.out.println(c.getTime());
return c.getTime();
}
Prints:
Tue Aug 06 00:00:00 EDT 2013
You can try with this also
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss 'GMT'");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}
Related
i am trying to compare two dates using "after" method in android. here is my two dates
currentDate :Fri Sep 12 00:00:00 GMT+05:30 2014
expDate :Tue Sep 01 00:00:00 GMT+05:30 2015
my code is as follows
private boolean checkDate(String date) throws ParseException{
Calendar c = Calendar.getInstance();
String cYear = String.valueOf(c.get(Calendar.YEAR)).substring(0, 2);
String digit1 = date.substring(2,4);
String digit2 = date.substring(0, 2);
String finalDate = cYear+digit1+"-"+digit2+"-"+"01";
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = curFormater.parse(finalDate);
String cDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
Date curentDate = curFormater.parse(cDate);
if(curentDate.after(expDate)){
return true;
}else{
return false;
}
}
but my if condition is always returns false. i don't know whats wrong with the code.
please some one help me about this..
thank you.
if i try the below code for eg:
i will set the date as Fri July 25 2014 10:00 AM. which gives date in milliseconds as 1402080056000,
now if i try to read the same milliseconds to date as below
long time = 1402080056000;
Date mydate = new Date(time);
mydate variable shows date as Sat Jun 25 00:10:56 IST 2014
String DateTimeString = DateFormat.getDateTimeInstance().format(new Date(time));
with the above statement in DateTimeString i get date as Jun 25 , 2014 12:10:56 AM
How to read the datetime present in 1402080056000 to Fri July 25 2014 10:00 AM
Just need to work on the format string,
String dateTimeString=
String.valueOf(new SimpleDateFormat("dd-MM-yyyy hh:mm").format(new Date(time)));
Explicitly set time zone:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = String.valueOf(dateFormat.format(millis));
Also, this would be useful Regarding Timezones and Java
try below code:
private String convertMilliToDate(long timestamp) {
DateFormat formatter = new SimpleDateFormat("YOUR DATE FORMAT");
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
return formatter.format(calendar.getTime());
}
Try this:
String date= DateFormat.format("dd/MM/yyyy hh:mm:ss", new Date(date_in_milis)).toString();
Date-time work is easier using the Joda-Time library, which works on Android.
long millis = 1402080056000L;
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( millis, timeZoneIndia );
DateTime dateTimeFrance = dateTimeIndia.withZone( DateTimeZone.forID( "Europe/Paris" ) );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
To parse a string as a date-time, search StackOverflow for "Joda parse" to find many examples.
I want to get time and date separately from timestamp.Please help me in these. My example of timestamp is 1378798459.
Thanks
//Try the following
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(YOUR TIMESTAMP VALUE)));
txtDate.setText(dateString);
//You can put your needed format here:
SimpleDateFormat formatter = new SimpleDateFormat("YOUR REQUIRED FORMAT");
Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
Improving upon the answer given by Pratik Dasa
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Here you can get various formats using the following syntax. You can play around with it by deleting or adding terms given below in the syntax.
Date and Time Pattern Result
----------------------------- ---------------------------------
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
String time = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_TIME);
String date = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_DATE);
Try this,
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();
Only that:
long timestampString = Long.parseLong("yourString");
String value = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
format(new java.util.Date(timestampString * 1000));
long dv = Long.valueOf(timestamp_in_string)*1000;// its need to be in milisecond
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma").format(df);
From here.
you can use this
Long tsLong = System.currentTimeMillis();
String ts = tsLong.toString();
long millisecond = Long.parseLong(ts);
datetimeString = DateFormat.format("MM-dd-yyyy hh:mm:ss a", new Date(millisecond)).toString();
timeString = datetimeString.substring(11);
dateString = datetimeString.substring(0,10);
String t2 = datetimeString.substring(20,21);
The datetimeString contains the Date Time AM/PM data
timeString will give you the substring which contains the time only and the dateString is substring for date
The String t2 will give you whether it is AM or PM in the clock
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String data =(hour+ ':'+ ""+minute+ ':'+"" +second+"" +""+"" +day+"" +"/" +(month+1)+"" +"/"+ +year);
Toast.makeText(getActivity(), "Time stamp:"+data,Toast.LENGTH_LONG).show();
DateFormat dateFormat = DateFormat.getDateTimeInstance();
when.setText(dateFormat.format(new Date(timestamp * 1000)));
The timestamp is multiplied by 1000 for converting the seconds into milliseconds.
All the answers are great and they mainly focus on converting the unix timestamp to milliseconds first, which is correct.
I struggled to apply that because I must use 1000L in the conversion (instead of 1000 only). Here's my working code with time zone conversion
// Set TimeZone
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy h:mm a", Locale.US);
dateFormat.setTimeZone(getDeviceTimeZone());
// Set time
Date date = new Date(timestamp * 1000L);
return dateFormat.format(date);
For Android API 26 and above, you can just do
return Instant.ofEpochSecond( timestamp )
.atZone(ZoneId.of( timezone ))
.toLocalDateTime()
.toString();
The very best way to get day and date from the timestamp is that:
java.util.Date dayAndDate = new java.util.Date( (long) yourTimeStamp * 1000);
// object coming as like: Tue Feb 09
String day = dayAndDate.toString().split(" ")[0];
String month = dayAndDate.toString().split(" ")[1];
String date = dayAndDate.toString().split(" ")[2];
I hope you will like my approach, if you have liked it, don't forget to give it an upvote, so that others will consider it.
If you want to use time like in a WhatsApp message, You can use this method,
public static String millisToDateChat(long time) {
long currentTime = System.currentTimeMillis();
long defe = currentTime - time;
long time_in;
if(time!=0){
time_in = time;
}else{
time_in = currentTime;
defe = 0;
}
int s = (int)defe/1000;
int m = (int)defe/(1000*60);
int h = (int)defe/(1000*60*60);
int d = (int)defe/(1000*60*60*24);
int w = (int)defe/(1000*60*60*24*7);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time_in);
Date date = calendar.getTime();
#SuppressLint("SimpleDateFormat") String formattedDate=(new SimpleDateFormat("HH:mm")).format(date);
#SuppressLint("SimpleDateFormat") String formattedYear=(new SimpleDateFormat("MMM d, ''yy")).format(date);
#SuppressLint("SimpleDateFormat") String formattedm=(new SimpleDateFormat("MMM d")).format(date);
if(d>365) {
return formattedYear;
}else if(s>172000){
return formattedm;
}else if(s>86400) {
return "Yest.";
}else{
return formattedDate;
}
}
I am having a date string 2012-11-21 13:11:25 which I get from local database. I have to convert this according to UTC settings and display it on a particular screen. So if its GMT+05:30 it should be displayed as 2012-11-21 18:41:25 on the screen. How can I do this conversion. I have checked some of the questions but that didn't work out.
I am able to get a Date object that returns something like Wed Nov 21 13:11:25 GMT+05:30 2012 after this I need to get the time as 18:41:25 and date as 11-21-2012
Thanks in advance
Your df and inputFmt must use the same format.
But I think you should do it like this:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);
Get UTC from current time :
public String getCurrentUTC(){
Date time = Calendar.getInstance().getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
Best way to get formatted string of Date in required format is
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = dateFormat.format(date);
//This is my input date
String dtStart = "2019-04-24 01:22 PM";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Date date = null;
try {
date = format.parse(dtStart);
getDateInUTC(date)
} catch (ParseException e) {
e.printStackTrace();
}
//This Method use for convert Date into some UTC format
public static String getDateInUTC(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateAsString = sdf.format(date);
System.out.println("UTC" + dateAsString);
return dateAsString;
}
I store current time in database each time application starts by user.
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?
Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.
update
Thanks all. I used following code:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
From String to Date
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
From Date to String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date
and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
You can use java.time in Android now, either by using Android API Desugaring or importing the ThreeTenAbp.
With java.time enabled, you can do the same operations with less code and less errors.
Let's assume you are passing a String containing a datetime formatted in ISO standard, just as the currently accepted answer does.
Then the following methods and their usage in a main may show you how to convert from and to String:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
ZonedDateTime odt = convert(dtStart);
System.out.println(odt);
}
and
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
OffsetDateTime odt = convert(dtStart);
System.out.println(odt);
}
will print the line
2010-10-15T09:27:37Z
when there are the corresponding methods
public static OffsetDateTime convert(String datetime) {
return OffsetDateTime.parse(datetime);
}
or
public static ZonedDateTime convert(String datetime) {
return ZonedDateTime.parse(datetime);
}
but of course not in the same class, that would not compile...
There's a LocalDateTime, too, but that would not be able to parse a zone or offset.
If you want to use custom formats for parsing or formatting output, you can utilize a DateTimeFormatter, maybe like this:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = ZonedDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss zz uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
which will output
Fri Oct 15 09:27:37 Z 2010
For an OffsetDateTime, you would need to adjust the pattern a little:
public static void main(String[] args) {
String dtStart = "2010-10-15T09:27:37Z";
String converted = OffsetDateTime.parse(dtStart)
.format(DateTimeFormatter.ofPattern(
"EEE MMM d HH:mm:ss xxx uuuu",
Locale.ENGLISH
)
);
System.out.println(converted);
}
This will produce a (slightly) different output:
Fri Oct 15 09:27:37 +00:00 2010
That's because a ZonedDateTime considers named time zones with changing offsets (due to daylight saving times or anything similar) while an OffsetDateTime just knows an offset from UTC.
It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);