Swift 2.0 String to NSDate - string

Hello i get my date from Datepicker that gets saved to a string then uploaded to Firebase. The string is then recieved to the phone. The problem is that i want to convert this string to NSDate when i retrieve it.
This is how i get a string from datepicker
func datePickerChanged(datePicker:UIDatePicker){
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var strDateFrom = dateFormatter.stringFromDate(datePicker.date)
fromDate = strDateFrom
print(fromDate)}
When i retrieve the date i get it as a string this is the print
print(self.membershipActiveTo)
And this is the print log
5/11/16, 2:35 PM
And below is the line of code i have tried to convert to string but it only returns nil
let strDate = self.membershipActiveTo // "2015-10-06T15:42:34Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
print ( dateFormatter.dateFromString( strDate ) )

There are things to consider when working with dates and one of them is how to store the date in a consistent format that can be easily worked with for different uses. In your case, you may want to sort by date and if the data is stored like this
5/11/16, 2:35 PM
It's not going to be sortable. So, a different format is needed and here's one possible example
20160511143500
Here's some code to manipulate dates:
Write a nicely formatted date to Firebase
let d = NSDate()
//create a custom date string & save in firebase
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let customDateString = dateFormatterCustom.stringFromDate(d)
print(customDateString) //prints "20160511023500" just for testing
let timesRef = self.myRootRef.childByAppendingPath("time_test")
let thisTimeRef = timesRef.childByAutoId()
let timeChildRef = thisTimeRef.childByAppendingPath("timestamp")
timeChildRef.setValue(customDateString)
Firebase now has this
time_test
-KFerAcANQv4pN1Pp4yW
timestamp: "20160418033309"
Then to read in from Firebase:
let timesRef = self.myRootRef.childByAppendingPath("time_test")
timesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
let timeStamp = snapshot.value.objectForKey("timestamp") as! String
print(timeStamp) //still looks like 20160418033309
let shortDateString = self.timeStampToDateString(timeStamp)
print(shortDateString) //prints 4/18/16, 3:33 AM
})
and the function that converts the timestamp style string to a human readable one
func timeStampToDateString(stamp: String) -> String {
//create a custom date string & create a date object from it
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.locale = NSLocale(localeIdentifier: "US_en")
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"
let d = dateFormatterCustom.dateFromString(stamp)!
//create a short date style string and format the string
let dateFormatterShortStyle = NSDateFormatter()
dateFormatterShortStyle.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatterShortStyle.timeStyle = NSDateFormatterStyle.ShortStyle
let dateString = dateFormatterShortStyle.stringFromDate(d)
return dateString
}
There's a lot of extra code in this example so it could be shortened considerably but I wanted to leave in all of the steps.

Related

mongoose js Data type

Hello i have a problem with mongoose JS date type. indeed when i set date to Type:Date and then use date function to get i Get the following format and I don't know why 2022-11-02T23:00:00.000Z.
I found a solution by setting type to string and using the following code :
clientSchema.pre('save',async function(){
let currentDate = new Date();
let currentDay = `${currentDate.getDate() < 10 ? "0" :""}${currentDate.getDate()}`
let currentMonth = `${currentDate.getMonth() + 1 < 10 ? "0" : ""}${currentDate.getMonth() + 1}`
let currentYear = currentDate.getFullYear();
this.date = `${currentDay}/${currentMonth}/${currentYear}`
})
But is this the best solution or is there another ?

tvOS - Override start time / end time slider AVPlayerViewController

I'm using AVPlayerViewController in order to play an HLS file, however the start time is always 00:00 and the end time is the duration of the event from the HLS manifest.
Instead I would wish to display the start time of the event and the end time of the event.
I found that can be used: AVKitMetadataIdentifierExactStartDate / AVKitMetadataIdentifierExactEndDate
But looks like when I create an AVMutableMetadataItem and I try to assign as identifier the AVKitMetadataIdentifierExactStartDate it doesn't exist. So I'm kind of stuck.
Anyone has any idea?
After few days of researches, I found that this can be achieved creating a AVMutableMetadataItem, assigning them as identifier an AVMetadataIdentifier(AVKitMetadataIdentifierExactStartDate) then as value you can just add the start time as date and cast everything as NSCopying & NSObjectProtocol.
Once you setup both properties you can append to the player.currentItem.externalMetadatas the new metadataItems that you just created as array of metadataItems.
Full example below:
//Add start date
let item = AVMutableMetadataItem()
item.identifier = AVMetadataIdentifier(AVKitMetadataIdentifierExactStartDate)
item.value = startDate as? NSCopying & NSObjectProtocol
let metadataItem = item.copy() as! AVMetadataItem
//Add start date
let endTimeItem = AVMutableMetadataItem()
endTimeItem.identifier = AVMetadataIdentifier(AVKitMetadataIdentifierExactEndDate)
endTimeItem.value = endDate as? NSCopying & NSObjectProtocol
let endTimeMetadataItem = endTimeItem.copy() as! AVMetadataItem
var metadataItems = [AVMetdataItem]()
metadataItems.append(metadataItem)
metadataItems.append(endTimeMetadataItem)
self.player.currentItem?.externalMetadata = metadataItems

How can I change the format of the ColumnField column headings in EPPlus?

I create a column field in EPPlus like so:
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
...that displays like so (the "201509" and "201510" columns):
I want those values to display instead as "Sep 15" and "Oct 15"
In Excel Interop it's done like this:
var monthField = pvt.PivotFields("MonthYr");
monthField.Orientation = XlPivotFieldOrientation.xlColumnField;
monthField.NumberFormat = "MMM yy";
...but in EPPlus the corresponding variable (monthYrColField) has no "NumberFormat" (or "Style") member.
I tried this:
pivotTableWorksheet.Column(2).Style.Numberformat.Format = "MMM yy";
...but, while it didn't complain or wreak havoc, also did not change the vals from "201509" and "201510"
How can I change the format of my ColumnField column headings in EPPlus from "untransformed" to "MMM yy" format?
UPDATE
For VDWWD:
As you can see by the comments, there are many things related to PivotTables which don't work or are hard to get to work in EPPlus; Excel Interop is a bear (and not a teddy or a Koala, but more like a grizzly) compared to EPPlus, but as to PivotTables, it seems that EPPlus is kind of half-baked to compared to Exterop's fried-to-a-crispness.
private void PopulatePivotTableSheet()
{
string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
AddPrePivotTableDataToPivotTableSheet();
var dataRange = pivotDataWorksheet.Cells[pivotDataWorksheet.Dimension.Address];
dataRange.AutoFitColumns();
var pivotTable = pivotTableWorksheet.PivotTables.Add(
pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE],
dataRange,
"PivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
// Row field[s]
var descRowField = pivotTable.Fields["Description"];
pivotTable.RowFields.Add(descRowField);
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
// Data field[s]
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
// Don't know how to calc these vals here, so had to put them on the data sheet
var avgPriceField = pivotTable.Fields["AvgPrice"];
pivotTable.DataFields.Add(avgPriceField);
var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
pivotTable.DataFields.Add(prcntgOfTotalField);
// TODO: Get the sorting (by sales, descending) working:
// These two lines don't seem that they would do so, but they do result in the items
// being sorted by (grand) total purchases descending
//var fld = ((PivotField)pvt.PivotFields("Description"));
//fld.AutoSort(2, "Total Purchases");
//int dataCnt = pivotTable.ra //DataBodyRange.Columns.Count + 1;
FormatPivotTable();
}
private void FormatPivotTable()
{
int HEADER_ROW = 7;
if (DateTimeFormatInfo.CurrentInfo != null)
pivotTableWorksheet.Column(2).Style.Numberformat.Format =
DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
// Pivot Table Header Row - bold and increase height
using (var headerRowFirstCell = pivotTableWorksheet.Cells[HEADER_ROW, 1])
{
headerRowFirstCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
headerRowFirstCell.Style.Font.Bold = true;
headerRowFirstCell.Style.Font.Size = 12;
pivotTableWorksheet.Row(HEADER_ROW).Height = 25;
}
ColorizeContractItemBlocks(contractItemDescs);
// TODO: Why is the hiding not working?
HideItemsWithFewerThan1PercentOfSales();
}
You can use the build-in Date format YearMonthPattern. which would give september 2016 as format.
pivotTableWorksheet.Column(2).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
If you really want MMM yy as pattern, you need to overwrite the culture format:
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL")
{
DateTimeFormat = { YearMonthPattern = "MMM yy" }
};
pivotTableWorksheet.Column(2).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
It doesn't seem that you can set the format on the field itself. You have to access through the pivot table object:
pivotTable.DataFields[0].Format = "MMM yy";
Any formatting applied to the underlying worksheet seems to be completely ignored.

Converting A NSDate Array to a String Array in Swift

I am a bit new to swift and IOS coding. I have a NSdate array which is retrieved from parse "CreatedAt" column. I need to convert that array to a string array so I can use it as an input for a text label in tableview cells.
//I try the below, I defined resultsDateArrayString as string array variable, and resultsDateArray as NSdate array variable.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
resultsDateArrayString = dateFormatter.stringFromDate(self.resultsDateArray)
cell.postDateTxt.text = self.resultsDateArrayString[indexPath.row]
This is a highly inefficient way of formatting the dates into a String since it instantiates a new NSDateFormatter each time. Consider creating a constant NSDateFormatter for the class as an optimisation.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.systemTimeZone()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
cell.textLabel!.text = formatter.stringFromDate(resultsDateArray[indexPath.row])
return cell
}
UPDATE 1
To get that hh:mm format that you've mentioned in your updated question, then simply delete the line formatter.dateStyle = .ShortStyle
I'd use a map function with NSDateFormatter wrapped around each date with the output format you want.
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = ...
var strings = dates.map{dateFormatter.stringFromDate($0)}

String to date Format in j2me

I have a String Wed, 22 Aug 2012 06:29:31 +0530 like this, now I want to convert this String to a date format and I need to display day an date Wed, 22 Aug 2012 like this and eliminating other remaining String?
I need to display the date on my LWUIT form Screen
String date = "Wed, 22 Aug 2012 06:29:31 +0530";
String shortDate = date.substring(0, 16);
You need to write the code manually by using the methods in java.util.Calendar, we did some formatters and localization API's in Codename One so you can look at our code for reference or just move to Codename One.
For this date formate "date_posted":"2012-04-19T16:45:33+01:00" i use the following code. You can customize it for your needs.
try {
String dateString = date_posted;
String[] dateArray = Util.split(dateString, "T");
String[] date = Util.split(dateArray[0], "-");
String[] time = Util.split(dateArray[1], ":");
Calendar calStart = Calendar.getInstance();
calStart.set(Calendar.MONTH, Integer.parseInt(date[1]) - 1);
calStart.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[2]));
calStart.set(Calendar.YEAR, Integer.parseInt(date[0]));
calStart.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
calStart.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calStart.set(Calendar.MILLISECOND, 0);
Date postDate = calStart.getTime();
post_time = postDate.getTime();
} catch (Exception ex) {
Logger.err("fromJSON", ex);
}
I use something like this :
String getDateString(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new String(/*Any format you need*/);
}
There is no specific method in j2me to convert string to date. So, that is not possible at all.

Resources