String to date Format in j2me - java-me

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.

Related

Flutter/Dart: Excel Date to Date Object

I am parsing an excel document in excel using the excel: ^1.1.5 package. In my sheet, i have a Date column and this Date is being received in my Flutter code in the following format
"44663"
rather than:
"2022/04/12"
How do I parse this to a format such as YY-MM-DD.
I have tried DateTime.parse(), but it throws an error that my date format is invalid.
I found the answer :
const gsDateBase = 2209161600 / 86400;
const gsDateFactor = 86400000;
final date = double.tryParse("44663");
if (date == null) return null;
final millis = (date - gsDateBase) * gsDateFactor;
print(DateTime.fromMillisecondsSinceEpoch(millis.toInt(), isUtc: true));

Apache POI Date Parsing One Second Off

I'm parsing an Excel spreadsheet with a date in it. The results from POI are off by 1 second compared to what's displayed in Excel.
The unformatted data in Excel is: 43261.5027743056
The cell in Excel has a format of: mm/dd/yyyy hh:mm:ss
The field in Excel displays as: 6/10/2018 12:04:00 PM
The POI parser (v 4.0.1 and 4.1.0 both) parse it as:
Value: 43261.502774305598
Format: mm/dd/yyyy\ hh:mm:ss
Result: 6/10/2018 12:03:59 PM
Here's my code:
private final DataFormatter formatter;
case NUMBER:
String n = value.toString();
if (this.formatString != null) {
thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString);
}
else thisStr = n;
break;
Am I doing something wrong?
The problem is not the binary floating point problem. This also exists but it should not impact seconds of time.
The problem is that your value 43261.5027743056 is not really exact the date time 06/10/2018 12:04:00 but 06/10/2018 12:03:59.700. So it is 06/10/2018 12:03:59 plus 700 milliseconds. You could see this if you would formatting the cell using the format DD/MM/YYYY hh:mm:ss.000 in Excel.
For such values there is a discrepancy between Excel's date formatting and apache poi's DataFormatter, which uses Java's date format. When Excel shows the date time value 06/10/2018 12:03:59,700 without milliseconds, then it rounds to seconds internally. So 06/10/2018 12:03:59.700 is shown as 06/10/2018 12:04:00. Java's date formatters don't round but simply don't show the milliseconds. So 06/10/2018 12:03:59.700 is shown as 06/10/2018 12:03:59.
Apache poi's DateUtil provides methods which rounds seconds. But those methods seems not be used in DataFormatter.
As workaround we could override formatCellValue of DataFormatter to do so.
Complete example:
Excel:
Code:
import java.io.FileInputStream;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.formula.ConditionalFormattingEvaluator;
import java.util.Date;
class ExcelParseCellValues {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("Excel.xlsx"));
DataFormatter dataFormatter = new DataFormatter() {
#Override
public String formatCellValue(Cell cell, FormulaEvaluator evaluator, ConditionalFormattingEvaluator cfEvaluator) {
CellType cellType = cell.getCellType();
if (cellType == CellType.FORMULA) {
if (evaluator == null) {
return cell.getCellFormula();
}
cellType = evaluator.evaluateFormulaCell(cell);
}
if (cellType == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell, cfEvaluator)) { //we have a date
CellStyle style = cell.getCellStyle();
String dataFormatString = style.getDataFormatString();
if (!dataFormatString.matches(".*(s\\.0{1,3}).*")) { //the format string does not show milliseconds
boolean use1904Windowing = false;
if ( cell != null && cell.getSheet().getWorkbook() instanceof Date1904Support)
use1904Windowing = ((Date1904Support)cell.getSheet().getWorkbook()).isDate1904();
boolean roundSeconds = true; //we round seconds
Date date = DateUtil.getJavaDate(cell.getNumericCellValue(), use1904Windowing, LocaleUtil.getUserTimeZone(), roundSeconds);
double value = DateUtil.getExcelDate(date);
return super.formatRawCellContents(value, style.getDataFormat(), dataFormatString, use1904Windowing);
}
}
return super.formatCellValue(cell, evaluator, cfEvaluator);
}
};
CreationHelper creationHelper = workbook.getCreationHelper();
FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
}
}
Result:
Description of value Floatingpoint value DD/MM/YYYY hh:mm:ss.000 DD/MM/YYYY hh:mm:ss
Your example value 43261,5027743056 06/10/2018 12:03:59.700 06/10/2018 12:04:00
Exact Datetime 12:04 43261,5027777778 06/10/2018 12:04:00.000 06/10/2018 12:04:00
Exact minus 500 ms 43261,5027719907 06/10/2018 12:03:59.500 06/10/2018 12:04:00
Exact plus 500 ms 43261,5027835648 06/10/2018 12:04:00.500 06/10/2018 12:04:01
Exact minus 501 ms 43261,5027719792 06/10/2018 12:03:59.499 06/10/2018 12:03:59
Exact plus 501 ms 43261,5027835764 06/10/2018 12:04:00.501 06/10/2018 12:04:01
You're doing this when you parse the cell value as a double. Not all decimal values can be represented exactly as doubles. The nearest double to 43261.5027743056 is 43261.502774305597995407879352569580078125, which rounds to the value you're seeing.

Swift 2.0 String to NSDate

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.

DateTime is rounded up to the next day using ExcelLibrary

The datetime I'm writing to Excel always get rounded up to the next day:
workSheet.Cells[0, 0] = new Cell(DateTime.Now, new CellFormat(CellFormatType.DateTime, #"HH:mm:ss"));
In the output Excel file the cell gets this value: 29/09/2013 00:00:00
The DateTime.Now from this example is 28/09/2013 19:42:23
I ended up passing the cell value as a string instead of as a DateTime:
workSheet.Cells[0, 0] = new Cell(DateTime.Now.ToString(#"HH:mm:ss:ff"),
new CellFormat(CellFormatType.DateTime, #"HH:mm:ss"));
If you are using the ExcelLibrary Project Source Code, you can fix this by:
Go to SharedResource Class in this location: [Project Source Code folder]\Office\BinaryFileFormat folder
Change the EncodeDateTime function as below:
public double EncodeDateTime(DateTime value)
{
double days = (value - BaseDate).Days;
//if (days > 365) days++;
return days;
}
Pass the DataTime object to the Cell with the prefered format:
worksheet.Cells[iIndex, j] = new Cell(((DateTime)cellValue), new CellFormat(CellFormatType.DateTime, #"dd/MM/yyyy"));
You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.
If oCell.Format.FormatType = CellFormatType.Date OrElse oCell.Format.FormatType = CellFormatType.DateTime Then
Dim d As Double = Double.Parse(oCell.Value)
Debug.print(DateTime.FromOADate(d))
End If

How to create a field of format dd/yyyy?

The field is like a DateField but instead its value is just the month and the year like '05/2011' : how to create such a field ?
In java-me, you can use the java.util.Calendar package for formatting the date.
Here is snippet from this tutorial on displaying the date and time in Java ME:
private void outputDateUsingCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
StringBuffer sb = new StringBuffer();
int day = calendar.get(Calendar.DAY_OF_MONTH);
sb.append(numberToString(day));
sb.append("-");
int month = calendar.get(Calendar.MONTH) + 1;
sb.append(numberToString(month));
sb.append("-");
sb.append(calendar.get(Calendar.YEAR));
StringItem item = new StringItem("Using Calendar", sb.toString());
mainForm.append(item);
}

Resources