This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Formatting a date in javascript
I am new to Javascript / JQuery...and right now all I am trying to do (to learn) is to make a page that extracts information from a google calendar (public) and displays the events along with start date + time plus end date and time. So far I have:
<script type="text/javascript">
$(document).ready(function () {
var baseURL = "https://www.googleapis.com/calendar/v3/calendars/qq3hkhn3dj8gt05q539smmk2go#group.calendar.google.com/events?key=AIzaSyB66zMow3CSeTdM1m_X_0Wj1JxCtSTd8kU&alt=json&callback=?";
$.ajax({
url: baseURL,
dataType: 'json',
success: function(result) {
console.log(result.items[0].created);
}
});
});
</script>
In my console, the output I see is:
2012-01-07T23:46:15.000Z
Now, what I want to do is, parse this date and time into a pretty looking string, something like "January 1, 2012" and same for the time. How should I proceed? I do not want to step outside JS / JQuery / AJAX.
Also, I would appreciate comments / feedback on my code so far - does this seem a normal / good way to do it, or should I approach it differently?
Thanks, let me know please!
You could try something like this:
var date = new Date(result.items[0].created);
date.toLocaleString();
The format of toLocaleString() is different by browser. If you want precise control over the format, try using a library such as Datejs, XDate, or the formatDate function provided by jQuery UI.
You need to parse date string and convert it to date. This date library in Javascript contains some useful functions for the conversion you need.
http://www.mattkruse.com/javascript/date/source.html
I think you can use getDateFromFormat function in this.
Related
I'm kinda new to Javascript.
My problem is the following : I have to implement a form that is generated by a js file, by taking the url and paste it inside my HTML. I have a date input, and I need to verify if the date is right, wether it is dd/mm/aaaa or mm/dd/aaaa.
If possible, without using regExp. I already made this function out of StackOverflow RegExp :
function validateDateRegExp(field){
var date=field.value;
var regExp1 = /^(((0[1-9]|[12]\d|3[01])[\s\.\-\/](0[13578]|1[02])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)[\s\.\-\/](0[13456789]|1[012])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])[\s\.\-\/]02[\s\.\-\/]((19|[2-9]\d)\d{2}))|(29[\s\.\-\/]02[\s\.\-\/]((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var regExp2 = /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/;
if(!(regExp1.test(date)||regExp2.test(date))){
alert(date);
document.getElementById('fld_CS_BuyingDate').value="";
}
}
I'm looking for a solution since 2 days, but the answers are not clear, or the problem is not the same.
Does anyone have any idea on how I could work that out ?
Thanks for the future answers
I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.
I am new to salesforce and I know my question sounds silly. But I need someone to tell me the direction I should go.
My question is how can I convert string or object like this
{Start_time__C:"2014-07-24T20:55:00.000+0000"}
and this
{perDiem: true}
into salesforce object. And then I can use create function in remoteTK.
I am currently building custom app on salesforce1. In my visualforce page, I need to create new record, which has datetime, and boolean as its fields.
Thank you in advance!
I don't know much about the remoteTK but before you deep dive into it you might want to look into the "Remote Objects" from Spring'14. This seems to be the new hip / official way of doing remoting (which doesn't mean I'm saying rTK is bad!) and slightly easier to use.
https://salesforce.stackexchange.com/questions/33072/visualforce-remote-objects
https://developer.salesforce.com/blogs/developer-relations/2014/03/spring-14-using-visualforce-remote-objects-with-canjs.html
http://andyinthecloud.com/2014/01/22/spring14-visualforce-remote-objects-introduction/
http://www.salesforce.com/us/developer/docs/pages/Content/pages_remote_objects_example_extended.htm
The main difference between them seems to be that you could use rTK in a non-visualforce page as underneath it just relies on REST callouts. The remote objects use a special VF tag so it's VF-only.
In the end I think it won't matter much which library you'll use. Sample remote object code:
// Create work order line item
var workOrderLineItem = new SObjectModel.WorkOrderLineItem__c();
workOrderLineItem.set('Description__c', 'Answering the question');
workOrderLineItem.set('Hours__c', answer);
workOrderLineItem.set('WorkOrder__c', result[0]);
workOrderLineItem.create(function(error, result, event)
{
// Errors?
if(error!=null)
alert(error);
else
alert('Success');
});
vs. the sample from remoteTK:
var objectType = 'Account';
var fields = {'Name': 'salesforce.com', 'Description':'CRM'};
client.create(objectType , fields,
function(response) {
getAccounts(function() {
$j.mobile.pageLoading(true);
$j.mobile.changePage('#mainpage', "slide", true, true);
});
}, errorCallback);
So a JavaScript object with fields is being created in both cases. For Booleans you should be good sending 'true' or 'false' strings.
For dates you might have to experiment a bit. Generally I've been passing Unix timestamp (miliseconds since Jan 1 1970), this seemed to work OK for me in REST calls or Visualforce Remoting (by which I mean #RemoteAction stuff, yet another tool).
The RemoteTKController.writeFields() seems to be using Date.valueOf(someString) when casting. This means the format should be 'yyyy-MM-dd HH:mm:ss' which is close enough - check if it will work out of the box and remove the timezone part from your string if it causes problems? You could simplify your examples a lot by skipping the remote part and directly check in Developer Console or Execute Anonymous how the parser reacts to different dates you'll feed it.
There's another function that seems to use REST API instead of the controller. This one will just pass the payload to REST API's POST request. Looking at how it's built you should be fine just passing a real JavaScript Date object as value, the JSON.stringify call should figure out how to serialize that. If you really want to craft the string yourself - check the REST API guide. The dates should look like that and all remoteTK'create call does is make a request similar to this one
This is an old thread, but in case it helps someone I was able to get this working. The yyyy-MM-dd HH:mm:ss format was very close. All it needed was a 'T' between the date and time to be acceptable. From there is was just making sure that all components came through as two digits, and converting the date to UTC time. Here's my final Javascript function:
function ConvertDate(dtin){
var d = new Date(dtin);
var convertdate = d.getUTCFullYear() + '-' + ('0' + (d.getUTCMonth()+1)).slice(-2) + '-' + ('0' + d.getUTCDate()).slice(-2) +'T' + ('0' + d.getUTCHours()).slice(-2)+':'+('0' + d.getUTCMinutes()).slice(-2)+':'+d.getUTCSeconds()+'0';
return convertdate;
}
From there I could pass the converted date to the sObject function without error.
I'm new to javascript and I've got this problem of showing dates.
I would like to display a readable date formatted like MM-DD-YYYY, but everytime I try to load the page, I always get an ASP format date.
Someone gave this code and I tried to use it on my project, yet, I still get the wrong format of date with this kind of error Uncaught TypeError: Cannot call method 'formatDate' of undefined.
What's wrong with this code?
$(document).ready(function () {
var date = $.datepicker.formatDate('yy-mm-dd', new Date($("#dateOfBirth").val()));
$("#dateOfBirth").val(date);
});
I'm using C# MVC.
Might give this a try (assuming you're using jQuery... If I'm way off, I apologize):
// You might not need the next two lines...
// And if not, just delete them as well as the last line
jQuery.noConflict();
jQuery(function($) {
$(document).ready(function() {
$("#dateOfBirth").datepicker();
$("#dateOfBirth").datepicker("dateFormat", "yy-mm-dd");
});
});
The question is; there are 2 fields in my application, one is date (Field1) and second is a label (Field2). So, I want that when user selects a date in field 1, then field 2 should be automatically populated (current date - date from field 1).
Can anyone help on how to implement it.
I'm using jQuery to display date:
// This displays the date dialog when user clicks on Field1
$('#Field1').click(function () {
$('#Field1').simpleDatepicker();
});
// Tried following code but it didn't worked
$('#Field1').click(function () {
$('#Field1').simpleDatepicker({
onSelect: function () {
$('#Field2').value(calculateDays($('#Field1').toString))
}
});
});
function calculateDays(dateString) {
var today = new Date();
var inputDate = new Date(dateString);
var days = today - inputDate;
return days;
};
This may look like pathetic code to some folks but I'm just a beginner, so any suggestions/comments are welcome.
Also please tell me if this can be done using html only and no need to go to jQuery. It is my understanding that the calculating days (difference between dates) code will go in jQuery since this needs to be fired after selecting date ('onSelect' event). Please correct if wrong.
I'm assuming that you're trying to use Karl Seguin's jquery.simpleDatePicker (it came top when searching for "simpledatepicker" on Google).
As Jimbo remarks in the comments, it's hard to advise on an MVC approach here — you say you want to do this purely with HTML, but HTML alone can't dictate behaviour (I'd say that's extremely un-MVC). HTML5 forms do allow some limited behavioural control (validation etc), and they also offer <input type="date"/>, but none of these help your situation.
So for this answer I'm just going to fix the mistakes in your code:
The plugin is initialised with the simpleDatePicker jQuery method — you forgot to capitalise the 'P';
The plugin itself caters for the click event. You should initialise it directly without waiting for user input;
There was no onSelect initialisation option in the source code: I chose to use a change event listener on the input to capture this;
You use the jQuery method value — that's native DOM Javascript — you should be using val instead;
toString won't work on DOM elements or jQuery objects — again, use the val method;
The native Date object can't parse dates in arbitrary formats — nor would your code produce a number of days if it did (it would just produce the difference in milliseconds). For this kind of functionality you should use a good date library: I've opted for Moment.
Resulting code (as demonstrated here):
$('#Field1')
.simpleDatePicker()
.on('change', function passValue(){
$('#Field2').val(calculateDaysFromNow($('#Field1').val()))
});
function calculateDaysFromNow(dateString){
return moment.duration(moment(dateString,'MMM DD YYYY').diff()).days();
}
A bit of elaboration on how I've used moment:
First of all, we want to parse #Field1's formatted date for an actual quantifiable date object:
moment(dateString,'MMM DD YYYY')
Next, we want to differentiate that from now. Like Date, moment assumes now if we pass no argument:
moment(dateString,'MMM DD YYYY').diff()
We don't want this as a date, but as a duration, so we'll pass it to moment's duration method:
moment.duration(moment(dateString,'MMM DD YYYY').diff())
…and finally, we want this expressed in days:
moment.duration(moment(dateString,'MMM DD YYYY').diff()).days()
I'm not sure but this:
$('#Field2').value(calculateDays($('#Field1').toString)) should be like this:
$('#Field2').value(calculateDays($('#Field1').val())) or $('#Field2').value(calculateDays($('#Field1').text()))
Here is solution for setting same date in second field.
Link:jquery: using two datepicker with two fields ( field 1 , field2 + 1 day ) like booking.com
Change the format according to your need.