Creating date using integers and displaying in a textbox [duplicate] - java

This question already has answers here:
Convert linux timestamp to android date
(4 answers)
Closed 5 years ago.
I am new to Android Studio and have ran into a problem - I am trying to carry out a calculation whereby I need the current date and time in an integer format. I also need the current date and time to then display in a TextBox.
I have declared the date as an integer as follows:
public static int date1 = (int) (new Date().getTime()/1000);
datedisplay = (TextView) findViewById(R.id.date);
Then I have tried to get the current date and time displayed in a textbox, but it isn't displaying. I was just wondering would anyone know why?
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
System.out.println(new Date(new Date(date1).getTime()));
datedisplay.setText(dateFormat.format(date1));
Thank you in advance

Use it in any datatype you want either String or Integer.
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
datedisplay.setText(timeStamp);

new Date().getTime() ; return long value if you diving it by 1000
to convert long to int
better if you use long:
long date1 = new Date().getTime() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));

You can also use Calendar class:
Calendar myCalendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm",Locale.getDefault());
String dateString = sdf.format(myCalendar.getTime());
then
datedisplay.setText(dateString);

If you really want to use a int to store your date representation, just use the number of day since the epoch instead of the number of seconds
new Date().getTime()
/1000 //second
/60 //minute
/60 //hour
/24; //day
This will give you a value that will fit in a int for quite some time.
But of course you won't be able to get back the exact precision, if you want the Time part of the Date, you won't be able to. This only allows you to get the Date like yyyy-MM-dd
private static final long EPOCH_DAY = 1000L * 60 * 60 * 24;
public static void main(String[] args){
int i = (int) (new Date().getTime()/EPOCH_DAY);
System.out.println(new Date(i * EPOCH_DAY));
}
Fri Nov 03 01:00:00 CET 2017
(the hours is because of my local being in GMT+1)

Related

How add 30 days in current date? [duplicate]

This question already has answers here:
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Closed 3 years ago.
I want to add 30 days in my current date I searched a lot but did not get the proper solution.
my code
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentdate = df.format(date);
try {
c1.setTime(df.parse(currentdate));
c1.add(Calendar.DATE, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(c1.getTimeInMillis());
String dueudate = df.format(resultdate);
Toast.makeText(this, dueudate, Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
}
The output of this code is :
2019-01-29
I don't why it is showing this output can anyone help me.
You need to use
c1.add(Calendar.DAY_OF_YEAR, 30);
instead of
c1.add(Calendar.DATE, 30);
Try this
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentDate = df.format(date);// get current date here
// now add 30 day in Calendar instance
c1.add(Calendar.DAY_OF_YEAR, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultDate = c1.getTime();
String dueDate = df.format(resultDate);
// print the result
Utils.printLog("DATE_DATE :-> "+currentDate);
Utils.printLog("DUE_DATE :-> "+dueDate);
OUTPUT
2019-06-04 14:43:02.438 E/XXX_XXXX: DATE_DATE :-> 2019-06-04
2019-06-04 14:43:02.438 E/XXX_XXXX: DUE_DATE :-> 2019-07-04
Another easier option, if on Java 8, use the java.time package which provides functions to perform plus/minus on current date of any units of time, example:
import java.time.LocalDate;
LocalDate date = LocalDate.now().plusDays(30);
//or
LocalDate date = LocalDate.now().plus(30, ChronoUnit.DAYS);
Calendar.getInstance() gives you the current time. You don't need to create another Date object for that.
Calendar current = Calendar.getInstance();
current.add(Calendar.DATE, 30);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(current.getTimeInMillis());
String dueudate = df.format(resultdate);
System.out.println("" + dueudate);
1)Go from date to millis.
2)Create a long variable with value 30L * 24L * 60L * 60L * 1000L.
3)Add this value to the millis you got in step 1
4) Go from this sum back to date again.
Edit: Variables that store millis should be long, not int.
Edit2: Adding "L" besides each number guarantees we won't get an overflow.

Get time from long value [duplicate]

This question already has answers here:
Android:Display time after adding GMT time zone
(2 answers)
Closed 4 years ago.
I am converting milliseconds to the time of the respective country time format, for example, pakistan, US etc
For example
timeinmilliseconds=1549362600000
So its respective Time formate from which I got these milliseconds is 15:30 or 3:30 in 12 hr format
When I want to convert these milliseconds back to that time
I get 10:30 (Five hrs back)
public String getTimeFromLong(long timeInMilliseconds){
String mytime="";
long minute = (timeInMilliseconds / (1000 * 60)) % 60;
long hour = (timeInMilliseconds / (1000 * 60 * 60)) % 24;
mytime = String.format("%02d:%02d", hour, minute);
return mytime;
}
If I select time 4:00
I converted to that to milliseconds (This part is OK)
And wants the time back from milliseconds but get five hours back
For example, If I select time 9:30
convert it to milliseconds and then to time
I get 4:30
You need to use your local time zone to get the time in your region, the default is being apllied which is the Greenwich Mean Time (GMT). For Pakistan use Asia/Karachi like so:
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("hh:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Karachi"));
Use this method to convert milliseconds into your local time
public String getTime(long time){
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(time);
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date date = new Date(time);
String kTime = format.format(date);
return kTime;
}
Using Java 8 we can do the following.
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
to get date and time
Use below code to get time from long values:
public String getTimeFromLong(long timeInMilliseconds){
// Creating date format
DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date result = new Date(timeInMilliseconds);
return simple.format(result);
}

Java get current day from unix timestamp [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 5 years ago.
I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?
The short solution is something like
long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));
it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference
You can use SimpleDateFormat to format your date:
long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
You can also convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
After doing it, you can get what you want:
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
You can calculate the date from a unix timestamp with java.util.Date
You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.
import java.sql.Timestamp;
import java.util.Calendar;
public class MyFirstJavaProgram {
public static void main(String []args) {
long unixTimeStamp= System.currentTimeMillis() / 1000L;
java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
Calendar cal = Calendar.getInstance();
// It's a good point better use cal because date-functions are deprecated
cal.setTime(time);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
}
Any further questions please leave a comment.

Strings with hh:mm format [duplicate]

This question already has answers here:
How can I calculate a time difference in Java?
(19 answers)
Closed 9 years ago.
I have two hh:mm strings, and I want to make comparisons between them.
I mean, I would want to add or subtract them, make operations. I have a string with the current time and another string that says, for example, "15:00". I want to know how many minutes there are between both strings, result that I can take by doing a subtraction.
Is that possible?
You can parse it by using SimpleDateFormat, then use the getTime() method from Date class to obtain the difference in milliseconds.
DateFormat f = new SimpleDateFormat("hh:mm");
Date d1 = f.parse(s1);
Date d2 = f.parse(s2);
long difference = d1.getTime() - d2.getTime(); // milliseconds
You could use joda datetime for this:
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
DateTime first = formatter.parseDateTime("15:00");
DateTime second = formatter.parseDateTime("15:49");
Interval interval = new Interval(first, second);
System.err.println(interval.toDuration().getStandardMinutes());
}
Have a look here
Using Duration also gives you some other neat methods like getStandardSeconds() which would give you 2940 for this case.
This will get you started.. Do the following for the two strings & then do the necessary comparisions/add/subtract
String time1 = "15:00";
String time2 = "16:00";
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date1 = sdf.parse(time1);
Date date2 = sdf.parse(time2);
long milliSecondsDiff = date1.getTime() - date2.getTime(); //in milliseconds
int seconds = milliSecondsDiff/1000; //seconds
int minutes = seconds/60; //minutes

How to convert 08:48 PM time into SQL unixtime?

How do I convert 08:48 PM formatted string into SQL Unixtime?
Java 1.5
You need java.text.SimpleDateFormat with the hh:mm a pattern (0-12 hours, minutes, AM/PM marker). Click the link to see the Javadoc with detailed pattern explanations.
String time = "08:48 PM";
Date date = new SimpleDateFormat("hh:mm a").parse(time);
long timestampMillis = date.getTime();
long unixTimestamp = timestampMillis / 1000;
If you actually want to store this in a SQL TIME/TIMESTAMP/DATETIME field with help of JDBC, then wrap it in a java.sql.Time and use PreparedStatement#setTime() to save it.
Time time = new Time(timestampMillis); // Yes, with millis!
preparedStatement.setTime(1, time);
// ...
Assuming you still want today's date, try
String today = new SimpleDateFormat("yyyy-MM-dd ").format(new Date());
long timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm a").parse(today + "08:48 PM").getTime() / 1000;

Categories