I'm receiving dates from my database in the format 2018-08-08 15:38:48 however I want it to show 3:38 pm instead.
I'm just unsure when to make this change, can I change it while it is being posted? They are dates of messages being sent to a person.
Current code:
<div v-for="messages in userMessages">
<div class="date">
{{ user.created_at }}
</div>
</div>
Output:
2018-08-08 15:38:48
How do I transform the date in vue? (when it is in a v-for?)
Vue does not offer date formatting. You will need your own filter to format the date. Or you use a package like the following: https://github.com/brockpetrie/vue-moment#readme
<span>{{ someDate | moment("hh:mm a") }}</span>
Vue.js does not natively allow dates to be formatted in a different way.
I suggest you to use more famous libraries like moment.js to format your dates however you want.
For example:
import moment from 'moment'
Vue.filter('formatDate', function(value) {
if (value) {
return moment(String(value)).format('MM/DD/YYYY hh:mm')
}
}
https://momentjs.com/
How do you use it?
You can use like this.
moment('2018-08-08 15:38:48').format('LTS'); // 03:38:48 PM
Your datetime format is not the ISO standard we would like, but we'll live with it... When handling dates, it's a good practice to convert them to date objects as soon as you receive them. If they're arriving in JSON, you can do this with a reviver function as the second argument to JSON.parse(). Here is a reviver function that will do the job for you...
Then,at the point you need to display, you can format your time with toLocaleTimeString()
function nReviver(key, value) {
var a;
if (typeof value === "string") {
a = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d*)?$/.exec(value);
if (a) {
return new Date(a[0]);
}
}
return value;
}
// do this when you receive your data from the server and all
// dates, wherever they are in the JSON, will be converted to date objects
var myObj = JSON.parse('{"myDate":"2018-08-08 15:38:48"}',nReviver)
// ...then, when you want to display, format with toLocaleTimeString()
console.log(
myObj.myDate.toLocaleTimeString({},{
hour12:true,
hour:'numeric',
minute:'numeric'
})
.toLowerCase()
)
Related
I have a javascript date that I am passing via ajax to a php script then using the date in an sql insert into mysql database. I can't figure out how to format the date so the SQL call accepts it. Can anyone help with this?
In the AJAX call I've tried passing the date object as is, converting to JSON, to UTC.
The error I get is:
Incorrect date value: 'Thu, 01 May 1902 03:01:00 GMT' for column 'uspr_dob'
This all works if I remove the date line from the SQL code. ie I update the other fields but not the date. So everything else is working except the date passing.
jQuery date formation:
var dob = new Date(year, month, day, hours, minutes, 0, 0);
jQuery AJAX call:
var save_result = jQuery.ajax({
url: lb_path + "update_user.php",
data: { 'lb_user_id' : this.id,
'lb_dob' : this.dob.toUTCString(), //toJSON
... },
type: 'POST',
datatype: 'json',
success: function(data, status) {
...
}, // End success
error: function (xhr, ajaxOptions, thrownError) {
...
}
}); // End load the supplement list
PHP code is:
$sql = "UPDATE userpref
SET uspr_person_group = \"".$lb_gender."\",
uspr_diet_type = (SELECT diet_id FROM diet WHERE diet_name = \"".$lb_diet."\"),
uspr_exercise_profile = (SELECT exprof_id FROM exercise_profile WHERE exprof_name = \"".$lb_exercise."\"),
uspr_dob = \"".$lb_dob."\"
WHERE uspr_user_id = ".$lb_user_id;
If you use YYYY-MM-dd format you will never run into any issues. It is better to convert it before passing it to the server in your case.
Please refer to Get String in YYYYMMDD format from JS date object? .
OK - I found the problem - The database documentation showed the field in the table was DATETIME ... when actually it was DATE.
Once I spotted that and massaged the datetime string into MySQL's format it all worked beautifully!
Still I would think that there is an easier way to do this ... ie a date format in javascript that can be passed straight through AJAX, PHP then SQL and work without any formatting.
Is there any way to get current timezone in Twig templates rather than passing from crontroller. This link gives the date for a specific timezone.
{{ post.published_at|date("m/d/Y", "Europe/Paris") }}
Maybe you could try a JS solution, like moment.js. You can assign a special CSS class (eg. date-transform) and run a script on all elements with this class:
$('.date-transform').each(function(){
var initialDate = moment($(this).html(), 'MMMM D, YYYY HH:mm');
if (initialDate.isValid()) {
var offset = moment().utcOffset(); // this is the client UTC offset
var finalDate = initialDate.add(offset, 'minutes').format('MMMM D, YYYY HH:mm');
$(this).html(finalDate);
}
});
highcharts gets my hour time wrong
I'm from venezuela just in case. I doing a real time system where I get in my db the time,seconds and miliseconds like
10:39:09:2
I apply the strtotime($time) then I sended by json to charted
and in my highcharts i got in the
xAxis: {
type: 'datetime',
title: {
text: 'Tiempo'
}
the utc function is already false
Highcharts.setOptions({
global: {
useUTC: false
}
});
and my function to get the json is
function requestData_Frecuencia() {
$.ajax({
url: 'Datos_Frecuencia.php',
success: function (point) {
var series = chart_Frecuencia.series[0],
shift = series.data.length > 400;
//add point
chart_Frecuencia.series[0].addPoint(eval(point), true, shift);
setTimeout(requestData_Frecuencia, 500);
},
cache: false
});
}
PS. is been a while since I write in english so forgive me if I write something wrong o that isn't clear.
You should check the raw values in the database. I know that MySQL stores dates in GMT. Not sure about the DB you are using, but the reason that this is done is:
GMT is an absolute time reference & doesn't change with the seasons.
You will have to convert the time to your locale, which is UTC–04:30
Have a look at: Convert date to another timezone in JavaScript
Highcharts doesn't include timezones and only what you can do is disabling UTC,aas you have. THen you need to translate your data or use label formatter / tooltip formatter to display correct data.
I found out what I was doing wrong (found the answer here ). I used to get my time in php like:
while($r2 = pg_fetch_array($sth)) {
$hora = $r2['hora'];
$Frecuencia = $r2['frecuencia'];
}
$x=strtotime($hora);
I needed to multiplied by 1000 the time. I think, is because I need to suggested that date is in form of miliseconds (that is integer)
while($r2 = pg_fetch_array($sth)) {
$hora = $r2['hora'];
$Frecuencia = $r2['frecuencia'];
}
$x=strtotime($hora)*1000;
PD: thanks to everybody anyway for the suggestion and responses given. I really appreciated
So here's what I'm trying to do - I have the following code:
<div id="on">
<p>We are: <span class="onair">ON AIR</span></p>
</div>
<div id="off">
<p>We are: <span class="offair">OFF AIR</span></p>
</div>
And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.
?
If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.
(Client side solutions work too if you dont care about where the time is coming from)
(1) You can have the server render javascript for you that you can use in a script
//if you want the server's time you can do this:
<?php $timestamp = time(); ?>
//render variables in javascript instead of html
<?php
echo <<<EOD
<script>
var timestamp = ${timestamp}
//then later in your javascript process the timestamp logic to update the dom
</script>
EOD;
?>
(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)
//onAirClass( min, max, timestamp ) returns className
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
if( timestamp >= timeMin && timestamp <= timeMax ){
return 'onair';
}
return 'offair'
}
//using onAirClass( min, max, timestamp )
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>
then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.
Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function
How to check the time between a given time range
UPDATED
Corrected PHP syntax errors
#maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:
var timestamp = $('#server-timestamp').text();
Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.
There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:
is simple
is efficient (doesnt do anything unnecessary or redundant)
falls in line with best practices
Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.
Here's a function you can use:
var onAir = function (day, start, end, timezone) {
var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;
// by default, we are not on air
onAir = false;
// map day numbers to indexes
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];
// convert start/end times to date objects
startValues = start.split(':');
endValues = end.split(':');
startTime = new Date();
endTime = new Date();
startTime.setHours(startValues[0], startValues[1]);
endTime.setHours(endValues[0], endValues[1]);
// add the hours minutes together to get total minutes
startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();
// get the current local time
local = new Date();
// get the current time in the show's timezone
utc = local.getTime() + (local.getTimezoneOffset() * 60000);
show = new Date(utc + (3600000*timezone));
// convert the show hours + minutes to just minutes
showMinutes = (show.getHours() * 60) + show.getMinutes();
// test to see if the show is going on right now
if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
onAir = true;
}
return onAir;
}
// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));
// now check if we are on air
if (texasShowOnAir) {
// do stuff here...
}
You can now use this function like this:
var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');
This will return a true/false. Be sure and use 24 hour format.
I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.
Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/
Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.
Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.
From the server:
<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>
On the client:
$(document).on('load', function() {
var serverTime = new Date($('#server-timestamp').text())
, clientTime = new Date()
, offsetMilliseconds = (clientTime - serverTime);
setInterval(function() {
// If server time is 3pm-4pm then hide/show divs...
}, 1000 /* every second */);
});
I have a page that shows future events along with the date (server time).
I need some method to display the date in user time.
Example:
Oct, 26 13:48:23 (server)
Oct, 26 14:48:23 (user time (UTC +1)) -> event info
What I have so far:
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo date('M, d H:i:s', strtotime ($row['date'])).' -> '.$row['info'];
}
?>
With the diffence I want to detect user timezone.
Thank you.
EDIT
I know I should not be using mysql_*
If you're ok with doing the conversion to the user's time zone in JavaScript, you could do the following:
PHP
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo '<span class="date">' . date('M, d H:i:s', strtotime ($row['date'])) . ' UTC</span> -> '.$row['info'];
}
?>
JavaScript (With jQuery for Readability)
$(function(){
$('.date').each(function(){
var $this = $(this);
// Parse the date string (the format you've given will
// work, and the added UTC above will give JavaScript
// some context)
var dateVal = new Date($this.text());
// JavaScript will convert it to the user's timezone when
// stringifying it (helped by the server timezone specified
// in the PHP.
$this.text(dateVal.toString());
});
});
If you want to render the dates in the format: Oct, 26 13:48:23, you could do this:
var dateString = dateVal.toLocaleString();
var parts = /^\w+ (\w+ \d{1,2}) \d{4} (\d{2}:\d{2}:\d{2})/.exec(dateString);
dateString = parts[1] + ' ' + parts[2];
Then use $this.text(dateString); to inject it into the dom.
You need to create DateTime object from this date, and then apply DateTimeZone to that object.
You would need to get the timezone from the user.
You can accomplish this by offering a dropdown with timezones that the user can select and submit. To make this a little more user friendly you could use some of the geoip functions to detect country and region and then determine a default timezone for the user. Do keep in my that location by IP is not 100% accurate but is instead an educated guess as to where the user may be located.
Alternatively you can use ajax to send the timezone to the server and then update accordingly.