Changing the format of a date in Yahoo UI - javascript

I'm using calendar from Yahoo UI as follows:
calDate = (calDate.getMonth() + 1) +
'/' + calDate.getDate() + '/' +
calDate.getFullYear();
This displays a MMDDYYYY format.
I want to change this format to YYYY-MM-DD so that I can insert it into a MySQL database.
I changed the code to:
calDate = calDate.getFullYear() + '-'
+ (calDate.getMonth() + 1) + '-' + calDate.getDate();
It worked but the problem is now that when I want to change the selected date the calender doesn't display the date and instead shows NAN.

It's typically best to pass the date to your back end as a unix timestamp and convert it in the database itself. In the code where you construct your POST data for the server, you'd pass something like this:
var t = calDate.getTime()/1000;
Note the divide by 1000. This is required because javascript timestamps are in milliseconds, while MySQL requires seconds.
In your SQL statement, you'll pass the timestamp as is, and use the FROM_UNIXTIME function to convert it to your required format:
INSERT INTO ... VALUES ( FROM_UNIXTIME($t), ...)
Naturally there will be some code in between that converts t from javascript into $t in your back end script, and then passes that on to the SQL.
Now, if you really need to format dates on the front end, you can make use of the handy YAHOO.util.Date utility. Just do something like this:
alert(YAHOO.util.Date.format(calDate, {format: "%Y-%m-%d" }));
Much easier than calling getFullYear, getMonth, and getDate

bluesmoon has also written two excellent articles on YUIBlog on the subject of date formatting:
http://yuiblog.com/blog/2009/02/11/date-formatting-pt1-2/
http://yuiblog.com/blog/2009/02/25/date-formatting-pt2/
-Eric

You should change the format of the date just before it is inserted on the server side, let the client side have the format that it wants, and change the date around later.

cal1.cfg.setProperty("DATE_FIELD_DELIMITER", "-");
cal1.cfg.setProperty("MDY_YEAR_POSITION", 1);
cal1.cfg.setProperty("MDY_MONTH_POSITION", 2);
cal1.cfg.setProperty("MDY_DAY_POSITION", 3);

Related

Convert an iso8601 time string to the current timezone in JS

I'm using the https://fullcalendar.io/ calendar plugin in an app. I provide the calendar with data with the dates in iso8601 format, like this, "2021-09-15T14:30:00+01:00", and the calendar does a good job of showing those times adjusted for the timezone set in the browser.
Eg, if the browser is in a "+01:00" timezone then that time shows up as 14:30, but if it's in a "+02:00" timezone it shows up as 15:30, etc.
My problem is that I'd like to show those times in other contexts, outside of the calendar, and I don't want to output different things from the server - I want the conversion to happen in the browser, using javascript.
It occurred to me that I could do something like this: output the time in a span with the iso861 string in a data attribute, perhaps with a class as well which acts as a trigger for some general js on the page. But, is there a simple way in JS to convert the iso8601 time string to a time using the browser's timezone setting? I suppose I would need to have another data attribute that has some info on how I want it to be formatted, something like "%H:%M" in this case (if I want to output "14:30" or "15:30").
Note - we use jquery and i will use that in my example JS below.
Something like this:
<!-- in html - the span contains the default unconverted time -->
<span class="convertable-time" data-iso8601="2021-09-15T14:30:00+01:00" data-datetime-format="%H:%M">14:30</span>
and then in the JS something like this (this is using jquery but the solution doesn't need to)
$(".convertable-time").each(function(i,el){
el = $(el);
el.html(convertIso8601StringToLocalTime(el.data("iso8601"), el.data("datetime-format"));
});
function convertIso8601StringToLocalTime(string, format){
//eg string = "2021-09-15T14:30:00+01:00"
//eg format = "%H:%M"
// ??
}
What would I put in the convertIso8601StringToLocalTime function?
Note - i'm not wedded to the exact format string of "%H:%M", if there is a more standard way of specifying a datetime format in JS then i'm happy to use it. thanks.
This is what I ended up doing:
//expects timestring to be an iso8601 formatted datetime string eg "2021-09-15T14:30:00+01:00"
//accepted strings for "format": copied from ruby's DateTime#strftime method
// %M - minutes
// %H - hours
// %S - seconds
// %d - day of the month
// %Y - year four digits
// %y - year two digits
// %m - month (as a number)
function convertIso8601StringToLocalTime(timestring, format){
//set default format
if((typeof(format) == "undefined") || (format == "")){
format = "%H:%M";
}
var date = new Date(timestring);
var replacements = {
"getMinutes": /\%M/g,
"getHours": /\%H/g,
"getDate": /\%d/g,
"getFullYear": /\%Y/g,
"getMonth": /\%m/g
}
for (const [function_name, regex] of Object.entries(replacements)) {
if(format.match(regex)){
format = format.replace(regex, date[function_name]());
}
}
// year two digits doesn't have a method we can call on a Date as far as I can see
// ('getYear()' returns '121' for me which is mysterious)
// so we do it 'manually' here by modding the full year by 100
if(format.match(/\%y/g)){
format = format.replace(/\%y/g, (date.getFullYear() % 100));
}
return format;
}

Output YYYY-MM-DD not full date string

I want to update a date linked by ngModel, using ngx-bootstrap datepicker, then send it in a PUT request to my Django backend. But the date format keeps getting changed from YYYY-MM-DD (2019-08-13) to the full javascript datestring (2019-08-13T23:00:00.000Z) which wont let me send the PUT request then.
I have tried nearly everything I can find on all other problems and it just doesnt work, nothing will let me select it as YYYY-MM-DD and keep it that way in the PUT request. Any help greatly appreciated.
<input class="form-control"
#dp="bsDatepicker"
bsDatepicker
[(ngModel)]="project.Start_Date2"
name="Start_Date2"
[bsConfig]="{
dateInputFormat: 'YYYY-MM-DD',
isAnimated: true,
containerClass: 'theme-default'
}">
I just want to be able to send my PUT request with the date format as YYYY-MM-DD. I am not sure if ngx-bootstrap will do it because when I pick a date with it, it converts it to the long string which then doesn't work in the PUT request.
The reason the date format keeps getting reverted is precisely because you use the ngModel, ie. two-way binding. The ngx-datepicker keeps pushing the selected value to your bound variable (Start_Date2). That is alright and expected.
I don't know how you do your PUT request, but you're going to need to do your format conversion either on the fly inside the request function or introduce another variable which will hold your date with the desired format.
I assume you use the angular HttpClient and the put request looks something like
this.http.put('https://example.com/dates/1', project.Start_Date2)
So what you can do is create a conversion function and convert the format inside the put call.
function myDateFormatFunction(inputDate) {
let d = new Date(inputDate) // this might not be needed if the date is already a Date() object
// YYYY-MM-DD
return d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); // the zeroes and slice weirdness is to have nice padding, borrowed from https://stackoverflow.com/a/3605248/3158815
}
this.http.put('https://example.com/dates/1', myDateFormatFunction(project.Start_Date2))

How to format MySQL timestamp using jquery

I read timestamp from MySQL db (is type timestamp).
Like this: 2017-04-01 15:34:31
I want to format this date using jquery and set up to some span element.
I am new in jquery and I don't know how to do it.
Thank you.
Try the DATE_FORMAT(date,format) function in MySQL. Something like:
DATE_FORMAT(NOW(),'%m-%d-%Y')
would give you 04-01-2017. Then wrap that in a <span>.
If you are using PHP then
strftime('%m-%d-%Y',$timestamp);
is an alternative. there are plenty of examples in Stack Overflow; Google will get you there.
If you would are receving the timestamp on the client side you can Convert a Unix timestamp to time in JavaScript
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
To add the formatted text to a span you could use javascript or jQuery
// Javascript
document.querySelector("span").text(formattedTime);
// jQuery
$("span").text(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.
Additionally:
If you must use jQuery instead of Javascript, consider a plugin
https://github.com/phstc/jquery-dateFormat
There is Javascript library https://momentjs.com/ for time
There is a great JS talk about time https://www.youtube.com/watch?v=2BdFg5JT9lg
Date(Date.parse(data.timestamp[i]))
This works assuming you are iterating through timestamps sent to the frontend from a Mysql query, which returns arrays. You could also write it like:
Date(Date.parse("2020-01-08 06:36:59"))

Convert datetime zone string to datetime javascript

I try to convert the format: 2017-03-07T17:26:15-03:00 to a format like
yyyy/MM/dd HH:mm:ss for i can use DateTime in MySQL DataBase. I receveid those values from a XML file.
I find a lot of options here, but not working, i'm using PDI from Pentaho to convert the XML and save in a Database.
Use JavaScript to convert a date string with timezone to a date object in local time
Thanks so much.
You can extract individual date parts and combine them to get the desired string. Something like this:
var d = new Date('2017-03-07T17:26:00-03:00');
var result = d.getFullYear()+
'/'+('0' + (d.getMonth()+1)).slice(-2)+
'/'+('0' + d.getDate()).slice(-2)+
' '+('0' + d.getHours()).slice(-2)+
':'+('0' + d.getMinutes()).slice(-2)+
':'+('0' + d.getSeconds()).slice(-2);
console.log(result);
You cant use the calculator step, create a copy of field A, wich is the date that you want to change, and select the format date that you want, sorry for my english, is rusty, regards

Manipulating Json string showing dateTime

Let me show you my code before I ask you my question,For your Info : meetings_String.TABLE[0].ROW[(j)].COL[5].DATA is dateTime object in sql server having format dd/mm/yyyy AM hh:mm:ss.....my code is
meetingsSDate=meetings_String.TABLE[0].ROW[(j)].COL[5].DATA; //meetingsSdate now has data in the format of 'dd/mm/yyyy AM hh:mm:ss'
Meet_startTime=meetingsSDate.replace(/\d\d\/\d\d\/\d\d\d\d /i,'');// Meet_startTime now has data in the format of 'AM hh:mm:ss'
I want to make another string using Meet_startTime(or otherwise) in javascript which will be of the format like HH:MM am or pm(24hr clock would be still better)
P.S:I hope you understand my question
It would be preferable to parse your values into actual Date objects, rather than just manipulating strings in different manners. From a Date object, you can extract the date and time parts and combine them in any order you want.
You could try...
meetingsSDate = meetingsSDate.split(' ');
Meet_startTime = meetingsSDate[2] + ' ' + meetingsSDate[1];

Categories