I do not know the reason why am i getting same values of different JSON date values.
Here is my code for parsing date values in JSON date format:
package com.jsondate.parsing;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class JSONDateParsing extends Activity {
/** Called when the activity is first created. */
String myString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
//Date d = (new Date(1266029455L));
//Date d = (new Date(1266312467L));
Date d = (new Date(1266036226L));
//String s = d.getDate() + "-" + d.getMonth() + "-" + d.getYear() + d.getHours() + d.getMinutes() + d.getSeconds();
// SimpleDateFormat sdf=new SimpleDateFormat("yyyy MMM dd # hh:mm aa");
//Toast.makeText(this, d.toString(), Toast.LENGTH_SHORT);
Log.e("Value:", d.toString());
myString = d.toString();
String []words = myString.split(" ");
for(int i = 0;i < words.length; i++)
Log.e("Value:", words[i]);
myString = words[2] + "-" + words[1] + "-" + words[5] + " " + words[3];
tv.setText(myString);
setContentView(tv);
}
}
As far as I know, there is no standard way of representing a date in JSON. It looks as though what you are receiving is an integral value representing the number of seconds that have elapsed since the epoch of January 1, 1970, 00:00:00 GMT. This is somewhat different than what the Date(long date) constructor is expecting. The constructor is expecting milliseconds since the epoch. You need to multiply the values from the JSON by 1000 to use them correctly with Date.
long jsonDate = 1266036226L;
Date date = new Date(jsonDate * 1000);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
String stringDate = dateFormat.format(date);
Here are the different representations for the examples that you have given. Do they correspond with what you are expecting?
1266029455 <==> 12-Feb-2010 09:50:55
1266312467 <==> 16-Feb-2010 04:27:47
1266036226 <==> 12-Feb-2010 11:43:46
1266072180 <==> 13-Feb-2010 09:43:46
Note that the default behavior of SimpleDateFormat is to use the local time zone. In my case this is GMT-0500. A different time zone can be specified by calling the setTimeZone method.
var d1 = ui.item.IssueDate;
var d = new Date(parseInt(d1.slice(6, -2)));
var Issdate = ("0" + (d.getMonth() + 1)).slice(-2) + '/' + ("0" + d.getDate()).slice(-2) + '/' + d.getFullYear().toString();
$('#IssueDate').val(Issdate);
Related
I'm trying to get to convert the decimals to a fraction so for example, I had written something such as var _pow:int = Math.pow(base,i) and if i turned out to be a negative number it would give out a decimal (example: 3 ^ -2) and I'm currently stuck trying to find a way to turn _pow into a franction (so _pow out of a 100) so I tried to do var _pow:int = Math.pow(base,i) * 100 which should stop it from being a decimal but it's not showing in the dynamic text, and this only happens if i is negative
package{
import flash.display.*;
import flash.events.MouseEvent;
public class name_ extends MovieClip{
public function _name_(){
btn.addEventListener(MouseEvent.CLICK, input)
base.restrict = "0-9\\.\\-";
pow.restrict = "0-9\\.\\-";
answer.multiline = true;
}
private function input(event:MouseEvent):void{
var pow = pow.text;
var base = base.text;
var answerText:String = "";
if(pow > 0){
for(var i = 1; i <= pow; i++){
_pow = Math.pow(base,i);
answerText += ("\n" + base + " exposant(power) " + i + " = "+ _pow );
answer.text = answerText;
}
}else{
for(i = 1; i <= pow; i++){
var _pow:int = Math.pow(base,i) * 100
answerText += ("\n" + base + " exposant(power) " + i + " = "+ _pow );
answer.text = answerText; //Dynamic text
}
}
}
}
}
Have you tried using an "if" statement? Something like if(i <= 0){code}.
You can also try using the Math.floor(number to be rounded down); or Math.ceiling(number to be rounded up)
I'm using JSF2 and PrimeFaces 5.1.
My problem is that I don't know how to put dates in the Y axis of my graph. It only accepts Number types.
/**
* Graph's definition
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel createLineModels() throws ParseException {
LineChartModel lineChartModel = new LineChartModel();
lineChartModel = initCategoryModel();
lineChartModel.setTitle("Graph's title");
lineChartModel.setLegendPosition("nw");
lineChartModel.getAxes().put(AxisType.X, new CategoryAxis("PV"));
Axis yAxis = this.lineChartModel.getAxis(AxisType.Y);
yAxis.setTickInterval("1");
yAxis.setLabel("Provisional dates");
return lineChartModel;
}
/**
* Initialization of the graph
* #return LineChartModel
* #throws ParseException
*/
public LineChartModel initCategoryModel() throws ParseException {
LineChartModel model = new LineChartModel();
ChartSeries provisionalDates= new ChartSeries();
provisionalDates.setLabel("Dates");
//Here, I set my data in the Graph
//In x-axis the date and the y-axis a numerical value
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
model.addSeries(provisionalDates);
return model;
}
My issue are those lines:
provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);
The method set only accept a Numerical value. I want to have date instead.
Do you know a way so I can put my dates in the Y axis?
Thanks
I finally found an answer with jqPlot.
The method set only accept a numerical value so what I did is to convert my date in milliseconds.
long dateMS= myDate.getTime();
provisionalDates.set("2016-01-15", dateMS);
Then, you can add an extender to your chart with PF. The extender allows you to configure your chart:
model.setExtender("extender"); //Works with PF 5+
After that, you just need to make the extender function:
function extender() {
this.cfg.axes.yaxis.tickOptions = {
formatter: function (format, value) {
return $.jqplot.sprintf(convertDate(value));
}
};
}
The convertDate function only convert a getTime to dd/mm/yyyy.
function convertDate(ms) {
var dateReadable = new Date(ms);
var year = dateReadable.getFullYear();
var month = dateReadable.getMonth() + 1;
if (month < 10) {
month = "0" + month;
}
var day = dateReadable.getDate();
if (day < 10) {
day = "0" + day;
}
return day + "/" + month + "/" + year;
}
My datagrid has a depth-dimensions column that shows fractions (one dimension used for example is 24 3/8). I have the ability to choose the text (fraction or decimal), but essentially I would need to be able to convert back and forth from 24 3/8 to 24.375.
Why the Decimal format is needed:
I have checkboxes to filter the depth-dimensions column, so I'll need decimal form for that logic (e.g. checkbox to see filter depth-dimensions between 20 and 26).
Why the fraction format is needed: I'll need the fraction format because that depth-dimension data will be referenced as a string in another part of the application. The filter doesn't work when in this format is used in the dataGrid, because it won't recognize 24 3/8 as a number/int.
So basically I'm looking for a way to convert between the two formats, 24 3/8 to 24.375 and 24.375 to 24 3/8.
Again, my apologies for the confusion - I'm able to re-edit and/or add more details if needed.
Thanks in advance!
--moe
Why the fraction format is needed: I'll need the fraction format
because that depth-dimension data will be referenced as a string in
another part of the application.
Your reason for needing the fraction format seems odd. Do you understand that you can use a Number data type in a String by casting it?
var decimalNum:Number = 3.14;
//concatenating a Number with a String automatically casts it
var autoCastString:String = "I want to eat some " + decimalNum;
trace(autoCastString);
// cast as String type
var decimalString:String = String(decimalNum);
trace("Mmmm! I like", decimalString);
Output:
I want to eat some 3.14
Mmmm! I like 3.14
But perhaps you have other reasons. The code below is from this link: Decimal to Fraction. I haven't tested it.
package com.lookmum.util
{
public class Fraction
{
private static var it :Number = 0;
public static var iterationLimit:Number = 10000;
public static var accuracy :Number = 0.00001;
public function Fraction()
{
}
private static function resetIt():void
{
it = 0;
}
private static function addIt():Boolean
{
it++;
if (it == iterationLimit)
{
trace('error : too many iterations');
return true;
}
else
{
return false;
}
}
public function getFractionString(num:Number):String
{
var fracString:String;
var fracArray:Array = getFraction(num);
switch (fracArray.length)
{
case 1 :
fracString = num.toString();
break;
case 2 :
fracString = fracArray[0].toString() + '/' + fracArray[1].toString();
break;
case 3 :
fracString = fracArray[0].toString() + ' ' + fracArray[1].toString() + '/' + fracArray[2].toString();
break;
}
return fracString;
}
public function getFraction(num:Number):Array
{
var fracArray:Array = new Array();
var hasWhole:Boolean = false;
if (num >= 1)
{
hasWhole = true;
fracArray.push(Math.floor(num));
}
if (num - Math.floor(num) == 0)
{
return fracArray;
}
if (hasWhole)
{
num = num - Math.floor(num);
}
var a:Number = num - int(num);
var p:Number = 0;
var q:Number = a;
resetIt();
while (Math.abs(q - Math.round(q)) > accuracy)
{
addIt();
p++;
q = p / a;
}
fracArray.push(Math.round(q * num));
fracArray.push(Math.round(q));
return fracArray;
}
}
}
I'm working with the youtube API and I'm getting the current time on the video as seconds.
What I want to do is to convert them into this: MM:SS
I've tried to google and try different things by myself but nothing seemed to work and be efficient.
I'll be glad to see how it can be done in a good and efficient way thanks in advance!
Something like:
var formattedTime =
(Math.floor(seconds/60)) + ":" + // minutes
(seconds % 60 >= 10 ? "": "0") + // padding for seconds if needed
(seconds % 60)); // seconds
here is a little class I use all the time just for what you need. I've also added a timecodes to seconds method. Simply use it like Timecodes.secondsToTimecode(634); which will output 00:10:34
package com.ronnieswietek.utils
{
public class Timecodes
{
public function Timecodes()
{
}
public static function timecodeToSeconds(tcStr:String):Number
{
var t:Array = tcStr.split(":");
return (t[0] * 3600 + t[1] * 60 + t[2] * 1);
}
public static function secondsToTimecode(seconds:Number):String
{
var minutes:Number = Math.floor(seconds/60);
var remainingSec:Number = seconds % 60;
var remainingMinutes:Number = minutes % 60;
var hours:Number = Math.floor(minutes/60);
var floatSeconds:Number = Math.floor((remainingSec - Math.floor(remainingSec))*100);
remainingSec = Math.floor(remainingSec);
return getTwoDigits(hours) + ":" + getTwoDigits(remainingMinutes) + ":" + getTwoDigits(remainingSec);
}
private static function getTwoDigits(number:Number):String
{
if (number < 10)
{
return "0" + number;
}
else
{
return number + "";
}
}
}
}
var timeStr:String;
//Video's length >= 1 hour
if( seconds >= 60*60 ){
//Format-> H:MM:SS
timeStr = (""+Math.floor(seconds/(60*60))) + //Hours
":"+
("0"+Math.floor((seconds%(60*60))/60)).substr(-2)+ //Minutes
":"+
("0"+(seconds%60)).substr(-2); //Seconds
}else{
//Format-> MM:SS
timeStr = ("0"+Math.floor(seconds/60)).substr(-2)+ //Minutes
":"+
("0"+(seconds%60)).substr(-2); //Seconds
}
Something a little easier to read to get your head around it:
var seconds:int = 200;
var minutes:int = 0;
while(seconds >= 60)
{
seconds -= 60;
minutes ++;
}
trace(minutes, seconds);
The leading zeros part can be done like so:
var secStr:String = String(seconds);
var minStr:String = String(minutes);
secStr = (secStr.length == 1) ? "0" + secStr : secStr;
minStr = (minStr.length == 1) ? "0" + minStr : minStr;
trace(minStr + ":" + secStr);
I'm trying to get a random date in a date range and this is what i have so far but it doesnt seem to be working ??
Where I'm I Going wrong ??
//Gets the date difference
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference; }
// gets a random number
function randomRange(max:Number, min:Number = 0):Number {
return Math.round(Math.random() * (max - min) + min); }
protected function getRandomDate:void {
// TODO Auto-generated method stub
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
var num:Number = new Number(differenceBetweenDates(dat2,dat1));
var random:Number= new Number(randomRange(num));
currDate.setDate(dat2.date+random);
getComic(formatDate(currDate));
dat2 = new Date(1989, 4, 16)
}
I found a couple errors in your code.
currDate.setDate(dat2.date+random)
setDate sets the date in the month, not an arbitrary date in time. Also, you want to use dat2.time, not dat2.date.
Should be
currDate.setTime(dat2.time+random)
Here's a slightly different version you might want to try out. I removed the MS_PER_DAY computation, so, you may want to add that back in if you need it, but I found this easier to look at:
public function getRandomTimeBetweenDates(date1:Date, date2:Date):Number
{
return Math.round(Math.random() * (Math.abs(date2.time - date1.time)));
}
public function getRandomDate():Date {
var dat1:Date= new Date();
var dat2:Date = new Date(1989, 4, 16)
dat2.setTime(dat2.time + getRandomTimeBetweenDates(dat2,dat1));
return dat2;
}