This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android - get date time from SMS timestamp in miliseconds
I am using the following code to record sms messages:
public void getColumnData(Cursor cur, Context context) {
ArrayList<String> exportBuffer = new ArrayList<String>();
try {
if (cur.moveToFirst()) {
String id;
String date;
String phoneNumber;
String body;
int idColumn = cur.getColumnIndex("_id");
int dateColumn = cur.getColumnIndex("date");
int numberColumn = cur.getColumnIndex("address");
int bodyColumn = cur.getColumnIndex("body");
do {
id = cur.getString(idColumn);
date = cur.getString(dateColumn);
body = cur.getString(bodyColumn);
phoneNumber = cur.getString(numberColumn);
String FormattedDate;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy");
FormattedDate = sdf.format(date).toString();
exportBuffer.add(id + " ," + FormattedDate + " ," + body + " ,"
+ phoneNumber);
} while (cur.moveToNext());
}
WriteToFile(exportBuffer,context);
} catch (Exception e) {
int MessageDuration = Toast.LENGTH_SHORT;
CharSequence text = "An Error Occurred, Code:104";
Toast toast = Toast.makeText(context, text, MessageDuration);
toast.show();
}
}
It all works fine apart from the date string I have no idea what format it is in which means I can't format it to a correct date here is an example of one of the dates:
1309817682651
Thanks in advance.
Try using this piece of code:
public static String millisToDate(long currentTime) {
String finalDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTime);
Date date = calendar.getTime();
finalDate = date.toString();
return finalDate;
}
Related
I have below Java code to convert string format to Timestamp object
public class TestUtil{
Object result;
Public Object convertFormat(String format, String value, String type){
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date = dformat.parse(value);
result = new Timestamp(date.getTime);
System.out.println("Result::"+ result);
}
}
Expected outcome:
I was expecting the outcome should be like below
20050225144824
Actual outcome:
2005-02-25 14:48:24.0
Could anyone tell me what I am missing here? To get "20050225144824" this result
The below code runs fine for me.
Adding few print statements to explain the different behaviors.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args) {
String myFormat = "yyyyMMddHHmmss";
String value = "20050225144824";
try {
SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dformat.parse(value);
Timestamp ts = new Timestamp(date.getTime());
Object result = new Timestamp(date.getTime());
System.out.println("Timestamp Format with yyyyMMddHHmmss : " +dformat.format(ts));
System.out.println("Object Format with yyyyMMddHHmmss : " +result);
System.out.println("Object Format with yyyyMMddHHmmss : " +dformat.format(result));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the output of the different behaviors :
Timestamp Format with yyyyMMddHHmmss : 20050225144824
Object Format with yyyyMMddHHmmss : 2005-02-25 14:48:24.0
Object Format with yyyyMMddHHmmss : 20050225144824
If you expect Timestamp to return your custom output then you need to override the default Timestamp library.
Here I create CustomTimestamp.java to extend Timestamp and override its toString() method. I modified the changes according to your requirement.
public class CustomTimestamp extends Timestamp {
private int nanos;
public CustomTimestamp(long time) {
super(time);
}
#Override
public String toString () {
int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
String yearString;
String monthString;
String dayString;
String hourString;
String minuteString;
String secondString;
String nanosString;
String zeros = "000000000";
String yearZeros = "0000";
StringBuffer timestampBuf;
if (year < 1000) {
// Add leading zeros
yearString = "" + year;
yearString = yearZeros.substring(0, (4-yearString.length())) +
yearString;
} else {
yearString = "" + year;
}
if (month < 10) {
monthString = "0" + month;
} else {
monthString = Integer.toString(month);
}
if (day < 10) {
dayString = "0" + day;
} else {
dayString = Integer.toString(day);
}
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
if (nanos == 0) {
nanosString = "";
} else {
nanosString = Integer.toString(nanos);
// Add leading zeros
nanosString = zeros.substring(0, (9-nanosString.length())) +
nanosString;
// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
truncIndex--;
}
nanosString = new String(nanosChar, 0, truncIndex + 1);
}
// do a string buffer here instead.
timestampBuf = new StringBuffer(20+nanosString.length());
timestampBuf.append(yearString);
timestampBuf.append(monthString);
timestampBuf.append(dayString);
timestampBuf.append(hourString);
timestampBuf.append(minuteString);
timestampBuf.append(secondString);
timestampBuf.append(nanosString);
return (timestampBuf.toString());
}
}
Your main class should use CustomTimestamp to get the output
try {
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date;
date = dformat.parse(value);
Timestamp result = new CustomTimestamp(date.getTime());
System.out.println("Result::" + result);
} catch (ParseException e) {
e.printStackTrace();
}
This question already has answers here:
How to get start and end range from list of timestamps?
(2 answers)
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
How to parse "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" date format to simple in Android? [duplicate]
(3 answers)
Closed 4 years ago.
String startDate = "2018-07-29T09:50:49+05:30";
String TAG = "Extra";
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMATE);
try {
Date date = df.parse(startDate);
System.out.println(TAG + "Start: " + date.getTime());
System.out.println(TAG + "Start: " + date.getDate());
System.out.println(TAG + "Start: " + date.getHours() + ":" + date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Its giving an error java.text.ParseException: Unparseable date: "2018-07-29T09:50:49+05:30"
Any idea what I am missing here?
The new API turns out to be even easier in this case. Your pattern is the default format for java.time.ZonedDateTime:
ZonedDateTime date = ZonedDateTime.parse("2018-07-29T09:50:49+05:30")
You can try something like this
String time="2018-07-29T09:50:49+05:30";
ZonedDateTime date = ZonedDateTime.parse(time);
System.out.println(date);
String TAG = "Extra";
System.out.println(TAG + "Start: " + date.getDayOfMonth());
System.out.println(TAG + "Start: " + date.toLocalDateTime());
System.out.println(TAG + "Start: " + date.getHour() + ":" + date.getMinute()) ;
You can use this method to get the date and time for your date:
Below are the different formats of dates, you can use your own and pass it to the method as params.
public String localFormat = "yyyy-MM-dd HH:mm";
public String alarmFormat = "yyyy-MM-dd-HH-mm";
public String defaultFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public String calendarFormat = "yyyy-M-d";
public String calendarFormatCh = "yyyy-M-dd";
public String calendarFormatRc = "yyyy-MM-dd";
public String reminderFormat = "dd/MM/yyyy hh:mm a";
public String getFormattedDate(Context mcontext, String date, String currFormat, String RequireFormat) {
Utils.e(Tag + "750", currFormat + "date " + date);
SimpleDateFormat sdf = new SimpleDateFormat(currFormat);
SimpleDateFormat sdfReq = new SimpleDateFormat(RequireFormat);
long time = 0;
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
time = sdf.parse(date).getTime();
return sdfReq.format(time).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
Just pass the date in the current format and in the format that you are expecting, it will return you accordingly. If you want time only, you can get using this method, you will need to implement it as per your requirement.
The Format you are using to parse has miliseconds too
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
You need to change that to
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ss.XXX";
I tried below example and it worked:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
String startDate="2018-07-29T09:50:49+05:30";
String TAG = "Extra";
final String TIMESTAMP_FORMATE = "yyyy-MM-dd'T'HH:mm:ssXXX" ;
DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMATE);
try {
Date date = df.parse(startDate);
System.out.println(TAG + "Start: " + date.getTime());
System.out.println(TAG + "Start: " + date.getDate());
System.out.println(TAG + "Start: " + date.getHours() + ":" + date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
ExtraStart: 1532838049000
ExtraStart: 29
ExtraStart: 9:1532838049000
This question already has answers here:
Display current time in 12 hour format with AM/PM
(15 answers)
Closed 4 years ago.
In this code show wrong time in case of 12:01:00 it shows 12:00 AM but right time is 12:00 PM:
private static final String sourceFormat = "hh:mm:ss";
private static final String targetFormat = "hh:mm a";
public static String convertTimeFormat(String dateStr) {
if (dateStr.equals("")) {
return "";
}
Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
SimpleDateFormat form = new SimpleDateFormat(sourceFormat);
Date date = null;
try {
date = form.parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat);
String newDateStr = postFormater.format(date);
Log.d("Lead Response", newDateStr);
return newDateStr;
}
Thank you very much for your time and assistance in this matter.
private static final String sourceFormat = "hh:mm:ss";
change to
private static final String sourceFormat = "HH:mm:ss";
It's working I checked in My IDE
private static final String sourceFormat = "HH:mm:ss";
private static final String targetFormat = "hh:mm a";
public static String convertTimeFormat(String dateStr) {
if (dateStr.equals("")) {
return "";
}
Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
**SimpleDateFormat form = new SimpleDateFormat(sourceFormat, Locale.US);**
Date date = null;
try {
date = form.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat, Locale.US);**
String newDateStr = postFormater.format(date);
Log.d("Lead Response", newDateStr);
return newDateStr;
}
I am using this code and getting the events from the calendar and it is working fine but, I want to get the events from google accounts calendar .For example, I want to get the (deepakcando90#gmail.com )google calendar accounts events also? I know it is possible but do not know how to implement it?
my code is ,
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("47:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
googleCalendar.setDtstart(dtstart1);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.