I want to view time from db and then save it to another db.table in timestamp format, but I've get different time every time I convert it:
print_r($sub_datetime['datetime']);echo "<br>";
$temptime = Yii::$app->formatter->asTimestamp($sub_datetime['datetime']);
print_r($temptime);echo "<br> ";
$temptime2 = Yii::$app->formatter->asDatetime($temptime);
print_r($temptime2);echo "<br> ";
$temptime3 = Yii::$app->formatter->asTimestamp($temptime2);
print_r($temptime3);echo "<br> ";
Get:
10-5-2015 10:00
1431252000
10-5-2015 13:00
1431262800
The Issue
asTimestamp function assumes that the date you have specified is UTC by default and gives out the UTC time value.
asDatetime function however thinks otherwise and gets the system timezone, giving you back the date with the system timezone offset.
Solution
You have a few options, any one will work
Set the yii formatter timezone to utc Yii::$app->formatter->timeZone = 'UTC'; before calling asDatetime function (and set back to original if needed).
Before passing the timestamp to asTimestamp, offset it by your timezone to convert it to UTC.
After getting the result of asDatetime, offset it by timezone in order to convert it back to UTC
Related
I have a use case where I have variable data in the following formats. When the string doesn't have time, the format object formats it with 12:00:00 => 12:00 am.
Well technically, the constructor that passes only a date IS instantiating it with a time, 12:00:00, even though it is implicit.
Example
'2021-02-12'
'2021-02-12T6:00'
'2021-02-19T18:00'
Code
const date = moment("2021-02-12");
date.format("h:mm a"); // 12:00 am
Expected
I'd like to know if that is possible that moment format the time with the empty string "" when time is not available in the data. e.g.
const date = moment("2021-02-12");
date.format("h:mm a"); // ""
Why Yii2 formatter asTime method return different time from asDateTime method?
Yii::$app->formatter->timeZone = 'Asia/Tehran';
date_default_timezone_set('Asia/Tehran');
var_dump(date_default_timezone_get()); //'Asia/Tehran'
var_dump(Yii::$app->timeZone); //'Asia/Tehran'
var_dump(Yii::$app->formatter->timeZone); //'Asia/Tehran'
var_dump(Yii::$app->formatter->asDatetime('now')); //'Aug 28, 2017, 3:22:25 PM'
var_dump(Yii::$app->formatter->asTime('now')); //'10:52:25 AM' Why it's different from the top
Since 2.0.12 Yii checks if value passed to asTime() contains information about time (hours, minutes, or seconds). If not (and now does not) it takes defaultTimeZone instead of timeZone (default is UTC).
If you want time in asDatetime() to be the same as asTime() you need to set Yii::$app->formatter->defaultTimeZone = 'Asia/Tehran'; but remember it might impact other code and database records saving.
Avoid time zone conversion for date-only asDate() and time-only asTime() values.
private function formatDateTimeValue($value, $format, $type)
I want to insert a Date object in mysql database, which has a Date type in the database as well. I am having problems inserting the date .
I have tried this code, but it seems codename one have a problem with it:
dateString s;
s = date.getCurrentMonth() + "/" + date.getCurrentDay() + "/" + date.getCurrentYear();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(s);
Please can you tell me how to do it ?
You don't need to format it. Just use this SQL Date Object instead of Date object from java.util package.
import java.sql.Date
// Creating a date object.
Date date = new Date();
In a database, make sure the data type of attribute 'date' is selected as "Date" also, not VarChar. Simply pass this sql package Date object into the database through query. :) It will save the date in a format.
I need to convert a date in milliseconds to a user readable date and I can't.
My date is: 1494519599999 which corresponds to: Thu May 11 2017 18:19:59 GMT+0200
I need to get something like dd/mm/yyyy HH:mm:ss
I have tried what I read in other stackoverflow posts:
DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");
But I always get 0 for year, month and more. I tought I should multiply or divide by 1000 the number but it was worst.
What is the correct way to do this?
The timestamp seems to be the value often used in JavaScript to represent a date (the number of milliseconds elapsed since January 1 1970). You can convert that to a DateTimeOffset using this code:
var timestamp = 1494519599999;
var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var dateTimeOffset = epoch.AddMilliseconds(timestamp);
The result is 05/11/2017 16:19:59 +00:00.
I am using a DateTimeOffset to make it easier for you to change the offset from +0000 to +0200. You can change the offset using this code where I assume you want to convert to local date and time. Windows Phone 8 does not support the full functionality of the TimeZoneInfo class so if you need to convert to another time zone you need create code the explicitely changes the offset:
dateTimeOffset = dateTimeOffset.ToLocalTime();
Now the result is 05/11/2017 18:19:59 +02:00.
If you prefer to use DateTime instead of DateTimeOffset you can use this code to create a UTC DateTime:
var timestamp = 1494519599999;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dateTime = epoch.AddMilliseconds(timestamp);
The result is 05/11/2017 16:19:59 and if your local timezone has a offset of +0200 you can convert it to a local DateTime to get the desired result. However, when time zones are involved I suggest that you use DateTimeOffset.
Try this:
var time = TimeSpan.FromMilliseconds(milliseconds);
I am pushing Values into a ko.observalbeArray with an AJAX call,
I want to format the JSON return date to "YYYY-MM-DD" before I am pushing it into my observableArray.
The Specific element in my Code that I want to convert is: OrderTimeStamp: element.OrderTimeStamp
Here is an example of a date that gets returned from server:
/Date(1377200468203+0200)/
Here is my AJAX call:
$.ajax({
url: "/[URL TO API Method]/GetAllOrdersbyparm",
data: {Parm: ko.toJS(MyDataViewModel.SelectedParmater), Start: ko.toJS(MyDataViewModel.ParmStart), End: ko.toJS(MyDataViewModel.ParmEnd)},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
MyDataViewModel.OrderDetails.push({ OrderID: element.OrderID, OrderGUID: element.OrderGUID, OrderTimeStamp: element.OrderTimeStamp, OrderStatus: element.OrderStatus, QtyProductsOnOrder: element.QtyProductOnOrder, PaymentDate: element.PaymentDate });
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
So, this is an ASP.NET specific Microsoft Date "standard".
See
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
why it should be avoided like the plague(1).
In that format the first component is a UTC milliseconds offset since the UNIX epoch.
The offset is TO local time, which is the opposite of the timezone offset in the JS Date string representations.
Use
var dateString = myDate.toJSON();
to serialize a JS Date object for sending.
Such a serialized datetime string, which is also in UTC (aka *Z*ulu), can be used to create a Date object thusly:
var myDate = new Date(dateString);
(1) In case you need to support this old ASP.NET Date format you can convert it to a proper JS Date like this (thanks [Roy Tinker][2]):
myDate = new Date(parseInt("/Date(1377200468203+0200)/".substr(6)));
I'm not familiar with that particular datetime notation.
Is that home-grown?
Is there documentation for that?
If not, then you are setting yourself up for trouble trying to interpret it.
That conversion toJSON would make it a UTC time and a few things are open for interpretation, unless documented in minute (no pun intended) detail.
So this is my answer: Be very sure you have the above definition in normative writing.
Now let me ramble on for a bit:
I went through that little exercise here...
http://en.wikipedia.org/wiki/ISO_8601 would be a good standard to base datetime notation on.
Now, you already get that format from the server, which looks like a millisecond time value since the epoch ('1970-01-01T00:00:00Z'), (probably with a timezone offset already applied to it!) combined with a timezone offset string in HHMM.
That's a bit scary, since those two components don't mix well.
Evaluated as an expression 1377200468203+0200 would subtract octal! 200 milliseconds! from 1377200468203. That's clearly not what's intended.
In ISO8601 (which this notation is not) this timezone offset would be FROM UTC, so the millisecond value would already have the 2 hour, 0 minutes offset applied to it.
Now the code could of course run on a machine which is in a different timezone than the datetime given.
The very crucial question is whether this millisecond datetime value has indeed the offset FROM UTC in it.
In that case, doing
var dt = new Date(1377200468203);
would be wrong.
If it is close to a daylight savings time switch time, it would be incorrect to just subtract to offset from it.
Note, not sure if below answers your question. If not, you may be helped by this one: How to format a JSON date?
Something along these lines should work:
var yyyy = element.OrderTimeStamp.getFullYear()
var mm = element.OrderTimeStamp.getMonth();
var dd = element.OrderTimeStamp.getDate();
var x = yyyy + '-' + (mm < 10 ? '0'+mm : mm) + '-' + (dd < 10 ? '0'+dd : dd)
element.OrderTimeStamp = x;
See this fiddle for an example. For reference, the MDN page has good documenation on Dates.
If you need more advanced date and time functionality I can recommend looking at MomentJS.