How to get given date format in phonegap? - android

I am new to phone gap.
I want to send date like a specific format to server.
I face problem to get the date format of given string.
For example i get the string like
20/04/2014 or
04/20/2014 or
2014/04/20 or
20 Apr 2014 ....
I mean i get the same date in different formats.i need to convert the date to a specific format,if it it is any format.
If any one know the solution.
Please help me.
Thanks in advance.

There is a related plugin cordova-plugin-globalization, I'm not sure whether it is what you need, but why not have a try?
https://github.com/apache/cordova-plugin-globalization/blob/master/doc/index.md
Hope this is helpful to you.

You can use,
var currentDate = new Date();
document.write(currentDate);
To return the current date.
(OR)
The Hard way...
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0, so always add + 1
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);
If you used this then you can format the date to the way you wanted.

Working Demo
It will give you in one format. check the fiddle with your example dates.
var d = new Date();
var c = new Date('20 Apr 2014');
alert(formatDate(c)); //This will give you proper one format date
alert(formatDate(d)); // This returns today's date
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return month + '-' + day + '-' + d.getFullYear();
}

Related

How to Get Date only or Time only output in react-native

I am developing an app in react-native.
I am using an npm package called react-native-modal-datetime-picker for collecting date. But the output i am getting is mixture of date and time
'Fri Feb 17 2017 16:06:00 GMT+0530 (IST)'
How cant collect only date in the format format="DD-MM-YY" from this.
I have faced same issues javascript should rename it to DateTime instead of just Date.
I would recommend you to use moment.js it will help you in timezones.
moment(new Date()).format("DD-MM-YYYY");
read more
If you have it as an Javascript Date object you could do this:
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
After that you can format it how you like. Just remember that getMonth() is from (0-11), so you can add one to the result to get it like a "normal" calendar.
var string = day + '-' + month + '-' + year;
onChange = (event, selectedDate) => {
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const currentDate = selectedDate || this.state.date;
this.setState({show: Platform.OS === 'ios'});
this.setState((this.state.date = currentDate));
// console.log('Month', currentDate.getMonth());
console.log('Date', currentDate.getDate());
var monthName = months[currentDate.getMonth()];
console.log(monthName);
// const Date = currentDate.toLocaleString('default', {month: 'long'});
// console.log('Date:', Date);
//Set Date
this.setState({currDate: currentDate.getDate()});
this.setState({currMonth: monthName});
};
For get a date few days forward from today {React TypeScript}: (It's also quite similar for previous date from today)
//This function is for calculating estimated Delivery Date
let date = new Date();
const estimatedDeliveryDate = (date: Date, day: number) => {
date.setDate(date.getDate() + day);
};
estimatedDeliveryDate(date, 3);
var estimatedDate =
date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();
console.log("Delivery Date: ", estimatedDate);

Best way to format a date relative to now on Android

I am creating a feature in an Android app to get an arbitrary date (past, present or future) and find the difference relative to now.
Both my now and due variables are longs, and this is my code:
long now = System.currentTimeMillis();
long due = now + 864000;
Log.d("Time in 1 day", DateUtils.getRelativeTimeSpanString(due,now, DateUtils.DAY_IN_MILLIS));
I want the output to be something like yesterday, today, in 4 days or 19/12/2012. However, the current output returns in 0 days...
I don't want the time to appear on these date strings.
What am I doing wrong and is the best method for formatting dates on Android?
What I have in mind is changing:
DateUtils.getRelativeTimeSpanString(due, now, 0L, DateUtils.FORMAT_ABBREV_ALL);
Since the documentation says it returns the time relative to now.
If that fails use some of the brilliant libraries:
Joda Time
PrettyTime
TimeAgo
Finally I have implemented what you wanted..!
First you need to download Joda Time from here
Extract it to any folder and put joda-time-2.2.jar into androidProject/libs folder.
MainActivity
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.MutableDateTime;
import org.joda.time.Weeks;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity
{
private int day ;
private int month ;
private int year ;
private int hour ;
private int minute ;
private long selectedTimeInMillis;
private long currentTimeInMillis;
private String strDay ="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
year = 2013;
month = 8;
day = 10;
hour = 15;
minute = 28;
DateTime selectedTime = new DateTime(year,month,day,hour,minute);
selectedTimeInMillis = selectedTime.getMillis();
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(selectedTimeInMillis); //Set to Epoch time
DateTime now = new DateTime();
currentTimeInMillis = now.getMillis();
int days = Days.daysBetween(epoch, now).getDays();
int weeks = Weeks.weeksBetween(epoch, now).getWeeks();
int months = Months.monthsBetween(epoch, now).getMonths();
Log.v("days since epoch: ",""+days);
Log.v("weeks since epoch: ",""+weeks);
Log.v("months since epoch: ",""+months);
if(selectedTimeInMillis < currentTimeInMillis) //Past
{
long yesterdayTimeInMillis = currentTimeInMillis - 86400000;
DateTime today = new DateTime(currentTimeInMillis);
int year = today.getDayOfYear();
int intToday = today.getDayOfMonth();
DateTime yesterday = new DateTime(yesterdayTimeInMillis);
int intYesterday = yesterday.getDayOfMonth();
DateTime selectedDay = new DateTime(selectedTimeInMillis);
int intselectedDay = selectedDay.getDayOfMonth();
int intselectedYear = selectedDay.getDayOfYear();
if(intToday == intselectedDay & year == intselectedYear)
{
strDay = "today";
}
else if(intYesterday == intselectedDay)
{
strDay = "yesterday";
}
else
{
strDay = "before "+ days +" days from today";
}
}
else if(selectedTimeInMillis > currentTimeInMillis) //Future
{
long tomorrowTimeInMillis = currentTimeInMillis + 86400000;
DateTime tomorrow = new DateTime(tomorrowTimeInMillis);
int intTomorrow = tomorrow.getDayOfMonth();
DateTime today = new DateTime(selectedTimeInMillis);
int intToday = today.getDayOfMonth();
if(intToday == intTomorrow)
{
strDay = "tomorrow";
}
else
{
days = -days;
strDay = "after "+ days +" days from today";
}
}
Log.v("strDay: ",""+strDay);
}
}
You just need to change the value of day and you will get the desire output.
Currently I have given date 10 as input so output will be today.
I have set date/day = 10 , month = 8 , year = 2013 , hour = 15 , min = 28
For past dates:
input day 9 output yesterday
input day 3 output before 7 days from today
input year 2012 and day 10 output before 365 days from today
For future dates:
input day 11 output tomorrow
input day 27 output after 17 days from today
input day 23 and year 2016 output after 1109 days from today
Why not just check for yesterday and tomorrow to avoid the in 0 days/0 days ago bug and leave DateUtils.getRelativeTimeSpanString handle the remaining cases?
String relative = null;
if(now < due && (due-now)<864000){
relative = "tomorrow";
}else if(now > due && (now-due)<864000){
relative = "yesterday";
}else{
relative = DateUtils.getRelativeTimeSpanString(due, now, DateUtils.DAY_IN_MILLIS); // e.g. "in 4 days"
}
Log.d("result", relative);
Edit: You may also add today with a simple check as well.
Best way to format a date relative to now on Android
I suggest you to use JodaTime
It's lightweight handy library and i think actually the best tool for working with Date instances.
And you can start here.
build.gradle
compile 'joda-time:joda-time:2.9.9'
Utils.java
private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, yyyy");
private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(" 'at' h:mm aa");
public static String getRelativeDateTimeString(Calendar startDateCalendar) {
if (startDateCalendar == null) return null;
DateTime startDate = new DateTime(startDateCalendar.getTimeInMillis());
DateTime today = new DateTime();
int days = Days.daysBetween(today.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays();
String date;
switch (days) {
case -1: date = "Yesterday"; break;
case 0: date = "Today"; break;
case 1: date = "Tomorrow"; break;
default: date = DATE_FORMAT.format(startDateCalendar.getTime()); break;
}
String time = TIME_FORMAT.format(startDateCalendar.getTime());
return date + time;
}
Output
Yesterday at 9:52 AM
Today at 9:52 AM
Tomorrow at 9:52 AM
Sep 05, 2017 at 9:52 AM
The actual reason is the number 864000 is in miliseconds, which corresponds to 14 minutes. 14 minutes is so small compared to DAY_IN_MILLIS (a day). There for you get "in 0 days".
If you want it to produce "in 14 mins", just change DAY_IN_MILLIS to MIN_IN_MILLIS.
I came here for an alternative but I can't find perfect rather than my code.
So I shared here any improvements are welcome.
public String getCreatedAtRelative() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("IST"));
CharSequence relative = null;
try {
relative = DateUtils.getRelativeTimeSpanString(df.parse(createdAt).getTime(), new Date().getTime(),
0L, DateUtils.FORMAT_ABBREV_ALL);
} catch (ParseException e) {
Log.e("Parse Exception adapter", "created at", e);
} catch (NullPointerException e) {
e.printStackTrace();
}
if (null == relative) {
return createdAt;
} else {
return relative.toString().replace(".", " ");
}
}
So your computation is based on milliseconds unit, then you format the result with SimpleDateFormat.
For this, you can easily use SimpleDateFormat formatter like this :
Date date = new Date(milliseconds);
SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM yyyy");
String strDate = formatter.format(date);
So your computation should be based on milliseconds unit, then you format the result with SimpleDateFormat.
The pattern ("EEEE dd MMMM yyyy") allows you to get a date format like Monday, 04 February 2013.
You can change the pattern as you like : "EEEE dd/MM/yy", ...
for Android you can use most simple way with Joda-Time-Android library:
Date yourTime = new Date();
DateTime dateTime = new DateTime(yourTime); //or simple DateTime.now()
final String result = DateUtils.getRelativeTimeSpanString(getContext(), dateTime);
long now = System.currentTimeMillis();
DateUtils.getRelativeDateTimeString(mContext, now), DateUtils.SECOND_IN_MILLIS, DateUtils.DAY_IN_MILLIS, 0)
a link!

Android Date displaying

I've a problem when displaying the date. I do everything fine, the date shows...bad it's not correct!
It says 2012/07/30 when it should be 2012/08/30.
I've checked my date in the mobile and it's correct. Do you have any idea?
Thank you!!
Piece of code:
Calendar c = Calendar.getInstance();
String sDate = c.get(Calendar.DAY_OF_MONTH) + "/" + c.get(Calendar.MONTH) + "/" + c.get(Calendar.YEAR);
view2.setText("" + et.getText() + sDate );
why don't you use DateFormat
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
view2.setText(dateFormat.format(c.getTime());
The Calendar object does not work as you are expecting it. The get(Calendar.MONTH) returns a constant representing the month of the date, not the number of the month. This subtle difference can be seen here:
java.util.calendar
As you will see, the constants reflect a zero-based sequence, starting with January, so that you can use the constants as indexers into an array for month-based lookups.
For your purposes, you could get away with adding 1 to the returned int, but you might want to look at SimpleDateFormat in the java.text. This article provides a brief overview to get you started.
Good luck!
You can instead use this,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String currentDateandTime = sdf.format(new Date())

How can I show today's date in an android activity?

I am currently working on my project for my professional course. I am implementing a digital diary.
I would be having a diary page (a multiline textbox maybe) And a TextView on top to show the current DATE (without time). How do I show a NON-editabale textbox with today's date shown in it.
In order to get the current date and time use the below Links and iin order make it non editable in XML file make editable = false also focusable = false.
LINK1
LINK2
its simple
Date dt = new Date();
int date = dt.getDate();
int month = dt.getMonth()+1;
int year = dt.getYear();
year += 1900;
int day = dt.getDay();
String[] days = { "Sunday", "Monday", "Tuesday","WednesDay", "Thursday", "Friday", "Saterday" };
String curDate = date + "/" + month + "/" + year + " " + days[day];
Use this code :
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
It 'll print :
Feb 5, 2013, 12:35:46PM

How to fetch current GMT value?

In my app, I am using GeoNamesAPI for fetching the current time at any location.
I have registered for using that.
My code looks like:
Timezone currentTimeZone;
org.geonames.WebService.setUserName("mathew");
currentTimeZone = GeoNamesAPI.fetchTimeZone(latitude, longitude);
The problem is when I check time at any ocean, this currentTimeZone returns null.
So in that case, I show the GMT value.
String time = null;
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
if (timeZone >= 0) {
time = "GMT+" + timeZone;
} else {
time = "GMT" + timeZone;
}
So the time value will be of the kind GMT+somevalue. I want to find another solution for this case. In this case also I want to display the time value. How can I do that? Is there any way to get the GMT value? Note: I dont want to show the date only time is required.
Thanks in advance.
I got it worked. Code is given below:
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
DateFormat dateformat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateformat.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, timeZone); //Adding/Subtracting hour to current date time
String newdate = dateformat.format(cal.getTime());

Categories

Resources