NSDateFormatter equivalent in Titanium / Convert date in specified format in Titanium - ios

I'm working with the date and time in my Titanium based iOS application.
My issue is, I'm getting the time in the below format:
Wed Jan 16 2013 17:32:40 GMT+0530 (IST)
I want to change it like:
Jan 16, 2013, 05:32 pm
In iOS there is NSDateFormatter for doing this.
What I did :
Currently I'm doing it manually using split and switch cases, but it fails if the input time format changes, then I need to re-write the code for the changed format.
I searched alot in Titanium Docs, but didn't get any solution.
I asked same question on their forum, didn't get any reply till now.
Is there is anyway to do this in Titanium?
Please help, Thanks in advance.

Look for moment.js JavaScript module for date formatting

I didn't find any alternatives for the NSDateFormatter in Titanium.
I tested the Moment.js, but it didn't worked for my case.
I implemented a JavaScript function for achieving my output.
/**
* Function for formatting the date and time
* #param {Object} dateTime
*/
function formatDateTime(dateTime)
{
var arr = dateTime.split(' ');
var convertedDate = arr[1]+' '+arr[2]+', '+arr[3];
var convertedTime = arr[4];
var returnValue = convertedDate+', '+convertedTime;
return returnValue;
}
Edit on 27 Feb 2014
After facing the JavaScript date formatting issue on different occasions, I finally developed my own JavaScript module, this module will format the JavaScript Date object to Specified formats. You can find it here : MMP_DateTime

I write one function which will convert date as per my requirement as given below
var getRequiredDate = function(date) {
var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear(); // Use standard date methods
var newdate = monthList[month] + ' ' + day + ", " + year;
Ti.API.info("Date :" + newdate);
};
Hope this helps you.

Related

Formatting a date with Moment Tz

I'm struggling with formatting a date to insert into a calendar. I'm working on an Ionic project and I'm attempting to leverage moment.js timezones. The data is being passed into the application in several pieces. I am receiving a millisecond date time stamp, a 24-hour string for time and a string of the timezone. The date does not contain the time. What I want to achieve is creating a date object from these pieces and then converting the date into the user's local timezone to add it to their device calendar.
example of data passed to app
The date of the event: August 14, 2018 17:00
time = 17:00
date = 1534204800
timezone = AEDT
The destination timezone is based on the user's location.
let timeFormatter = new Date();
timeFormatter.setMilliseconds(date);
let momentHrMin = moment(timeFormatter.toDateString() + " " + time);
//WP sever is on GMT get the day, month and yr
let momentTZDate = momentTz.unix(date);
momentTZDate.tz('GMT');
let day = momentTZDate.days();
let month = momentTZDate.month();
let yr = momentTZDate.year();
//set the correct timezone on the ecpoh/unix DATE with momentTz.
momentTZDate.tz(this.eventDetails.eventDetail.timezoneOffset);
// Lastly set the date so the timezone conversions are correct
momentTZDate.set(
{
day: day,
month: month,
year: yr,
hour: momentHrMin.hour(),
minute: momentHrMin.minute(),
second: 0,
millisecond: 0
}
);
I found the cause of my struggles with the timezones. The abbreviated AEDT is not an accepted value for Moment.tz. AEDT could represent multiple timezones. For example, American Eastern, Australian Eastern, etc... Simply changing momentTZDate.tz("AEDT"); to momentTZDate.tz("Australia/Brisbane"); fixed my issue. Below is my typescript code I used to get through this issue. I won't say its the best but it works.
private getCalDate(date:number, time: string): Date {
// create an object in which the hours and minutes can be parse from(do to free text entry on the backend moment handles different inputs)
let timeFormatter = new Date();
timeFormatter.setMilliseconds(date);
let momentHrMin = moment(timeFormatter.toDateString() + " " + time);
//WP sever is on GMT get the day, month and yr
let momentTZDate = momentTz.unix(date);
momentTZDate.tz('GMT');
let day = momentTZDate.days();
let month = momentTZDate.month();
let yr = momentTZDate.year();
//set the correct timezone on the ecpoh/unix DATE with momentTz.
momentTZDate.tz("Australia/Brisbane");
// Lastly set the date so the timezone conversions are correct
momentTZDate.set(
{
day: day,
month: month,
year: yr,
hour: momentHrMin.hour(),
minute: momentHrMin.minute(),
second: 0,
millisecond: 0
}
);
return momentTZDate.toDate();
}

Date with Time only get's NULL

I am using the Grails plugin, http://grails.org/plugin/jquery-date-time-picker
The date and datetime plugin works perfectly well. However, just time has an issue.
I tried to use time only for the datetimepicker. My Config.grovy is as below.
jqueryDateTimePicker {
format {
java {
datetime = "dd/MM/yyyy HH:mm"
date = "dd/MM/yyyy"
}
picker {
date = "'dd/mm/yy'"
time = "'hh:mm tt'"
}
}
}
My GSP code is something like.
<jqueryPicker:time name="openFrom" id="openFrom" value="${addressInstance?.openFrom}" pickerOptions="[dateFormat: '', timeOnly: true, hourGrid: '4', minuteGrid: '15', timeFormat: 'hh:mm tt']"/>
My Controller is
def addressInstance = new Address(params)
Here in the controller, i can see the params having the time as "7:00 am" but it never gets set in the addressInstance, i believe cause the date is missing.
The default Date binding takes the general date format as yyyy-MM-dd hh:mm:ss.S.
In order to to bind openForm date to addressInstance, you can explicitly set it as:
//where params.openForm is String like "7:00 AM"
addressInstance.openForm = Date.parse("h:mm a", params.openFrom)
Date.parse() parses the string as current format to return a Date object. In the aboved case(where you are only concerned about the time), you would end up with the epoch (Jan 1, 1970) with time as 7 AM.
def date = Date.parse("h:mm a", "7:00 AM")
//prints Thu Jan 01 07:00:00 EST 1970
//To get the time string from the date stored in db
date.format("h:mm a") //Prints 7:00 AM
You can also see if you can register a Custom property Editor as shown here to auto bind the date with customized format. You would not like to follow this if you do not want to apply the format to all date strings. In that case, I think the former approach will be useful and easy.

How to get long value from this date format "MMM dd, yyyy" on blackberry

I got response from Server as below
<reminder><text>Hello Dude!</text><date>June 2, 2011</date></reminder>
I parsed the info successfully. Now i need to add the info on blackberry reminder.
I used below code:
try
{
Event _event;
String Calenderevent = "Hello Dude.";
EventList eventList = (EventList) PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.WRITE_ONLY);
_event = eventList.createEvent();
long l= HttpDateParser.parse("June 2, 2011");
_event.addString(Event.SUMMARY, PIMItem.ATTR_NONE,Calenderevent);
_event.addDate(Event.START, PIMItem.ATTR_NONE, l);
RepeatRule rule = new RepeatRule();
rule.setInt(RepeatRule.FREQUENCY,RepeatRule.YEARLY);
_event.setRepeat(rule);
//If you need to repeat the event then use repeatrule.
_event.commit();
Dialog.alert("Calendar event success.");
}
catch (PIMException e)
{
Dialog.alert("Exception: "+e);
e.printStackTrace();
}
When I saw in Blackberry calendar, the info show in Dec 31, 2011
The problem occur is in below line.
long l= HttpDateParser.parse("June 2, 2011");
It returns -1 value.
How to get long value from this date format "MMM dd, yyyy" on blackberry.
Pls help me.
As Joel noticed, you date format is not supported by HttpDateParser. One possible solution would be to convert your date to one of formats that HttpDateParser supports and then parse it with parse() method.
This code converts your date to Wdy, Mon DD YYYY HHMMSS format first and then parses it.
String date = "June 2, 2011";
String time = "120000"; // desired time HHMMSS
long l = 0;
try {
StringBuffer sbDate = new StringBuffer();
// append WEEKDAY. weekday is not relevant for the HttpParser.
sbDate.append("Sun, ");
// remove comma after month
int commaIndex = date.indexOf(",");
sbDate.append(date.substring(0, commaIndex));
sbDate.append(date.substring(commaIndex+1));
sbDate.append(' ').append(time);
l=HttpDateParser.parse(sbDate.toString());
} catch (IndexOutOfBoundsException e) {
// the date is in wrong format
}
From the tests I made, Wdy is not taken into account by HttpDateParser. It returns the correct result with any valid weekday. This make sense for me, since what is really needed is DAY, MONTH and YEAR.

Convert date into julian date

I want to convert todays date into the julian date format . Suppose if the date is 31/12/2011(31st dec 2011) , then the julian date should be 11365(yyddd) .
Any help would be much appreciated
Thanks
One simple way to get the date in yyddd format would be doing some mathematics:
date theDate = 31\12\2011;
int theOrdDate;
;
theOrdDate = 1000 * (year(theDate) mod 100) + dayOfYr(theDate);
// or
theOrdDate = 1000 * (year(theDate) - 2000) + dayOfYr(theDate);
EDIT: one possible drawback: this calculation will return only 4 digits if the year is less than 2010.
In AX2012 this task is super easy.
str myJulian;
myJulian = date2Julian(today());

jQuery datepicker UI getdate() - How do I just output date only and NOT Wed Oct 06 2010 17:00:00 GMT-0700 (Pacific Daylight Time)

Currently this code is working but not as expected:
$("#start_date").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(_date, _datepicker)
{
var myDate = new Date(_date);
myDate.setDate(myDate.getDate()+8);
$('#estimated_hatching_date').text(myDate);
alert( myDate);
}
});
The first issue is, how the date is presented. Currently that code above alerts Fri Oct 01 2010 17:00:00 GMT-0700 (Pacific Daylight Time). I would like the output to be just the date, for example, 09/06/2010.
The second issue is, $('#estimated_hatching_date').text(myDate); does not change the text. When that code is fired nothing is changed. However if I do: $('#estimated_hatching_date').text('myDate'); myDate is placed into the #estimated_hatching_date div.
So, how do I just output the date and replace the "text" inside of #estimated_hatching_date div with just the date +7 days from when a date is selected?
Thank You,
Rich
jQuery UI Datepicker has a built in formatDate function. Please #dottedquad, don't use your self-made version, date math and formatting is harder than you imagine. The corner cases will make you tear your hair out.
onSelect: function(_date, _datepicker) {
var myDate = new Date(_date);
var myText = $.datepicker.formatDate('dd-mm-yy',myDate);
alert(myText);
}
I read over the ui datepicker manual again and figured it out.
$("#start_date").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(_date, _datepicker)
{
var myDate = new Date(_date);
myDate.setDate(myDate.getDate()+8);
var fullYear = myDate.getFullYear();
var month = ((myDate.getMonth()+1) < 10) ? ('0' + (myDate.getMonth()+1)) : myDate.getMonth()+1;
var day = (myDate.getDate() < 10) ? ('0' + myDate.getDate()) : myDate.getDate();
var myNewDate = fullYear + '-' + day + '-' + month;
$('#estimated_hatching_date').text(myNewDate);
alert(myNewDate);
}
});
That code works as expected. Anyone else have any more ideas that would get that job done differently?
-Thank You,
Rich
I had the same problem and used "altField" option with a hidden input. Hidden input's value is always formatted according to "dateFormat"

Resources