简体   繁体   中英

Quick question about date formatting php/javascript

I'm failing a bit to get this working.

I read out a date from my database in the yyyy-mm-dd format. However, I need to use it in my jQuery ajax call in the dd-mm-yyyy format. Is there a way to turn my dates around? I should've seen this coming when I started working on my app, but alas, I didn't :(

Don't feel like changing around the way I save stuff to my DB so I was wondering if anyone knows an easy way to change the format? Thanks :(

EDIT: Just ran into another, similar problem

I read time out as, for example, 08:00:00 I want to split this into parts aswell. For example

08:00:00 => var a = 8, var b = 00 // ignore seconds

09:30:00 => var a = 9, var b = 30

23:45:00 => var a = 23, var b = 45

10:30:00 => var a = 10, var b = 30

:( Thanks!

Format your date directly in your sql query :

SELECT DATE_FORMAT(fielddate,'%d-%m-%Y') as jsDate, DATE_FORMAT(fielddate,'%m-%d-%Y') as phpdate FROM xxx

You can do multiple format in the same query to fit your need (a format for js , one for php, one for direct display ...)

See date and time function

In PHP you can easily turn it around.

$date=date('d-m-Y', strtotime('2009-11-12'));

You could also achieve this using Javascript:

var date='2009-11-12'.split('-').reverse().join('-');

jsFiddle Demo

EDIT concerning your update:

var timeArray=myTime.split(':'); is what you need here. It grabs a string, and returns a normal array with the elements of the string splitted by : . So timeArray[0] will be the hour, timeArray[1] the minute.

Yes, you can turn it around, but yyyy-mm-dd is the internationally accepted way to represent dates in computers, so you really should not.

Instead, you should change your database, and if you want to present the date to the user in another format, you do the conversion for the presentation only.

EDIT: Sorry if this answer sounds rude, but I really believe that you will thank me later if you do this. Or at least keep it in mind until next time :)

使用日期功能:

date("d-m-Y",strtotime($yourdate));
<?php 

$newdate = date('d-m-Y',strtotime($db_date))


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM