In my javascript i enter date in below format as string
12.12.2014
I want to convert to JSON date format like below
/Date(1358866800000)/
How could i achieve this. I tried below code which converts to JSON format but doesnt work.
function convertToJSONDate(strDate){
var dt = new Date(strDate);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';
}
When i try to use above function like convertToJSONDate("12.12.2014"), i get date like this '/Date(NaN)/
How could i achieve this?
The string you are passing to Date's constructor is not valid
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
var dt = new Date(splitted[2],splitted[0],splitted[1]);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';
}
convertToJSONDate("12.1.2014");
Another simplified version could be:
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
//var dt = new Date(splitted[2],splitted[0],splitted[1]);
var newDate = new Date(Date.UTC(splitted[2], splitted[0], splitted[1]));
return '/Date(' + newDate.getTime() + ')/';
}
convertToJSONDate("12.1.2014");
#AlexBcn Great answer, but you need to subtract 1 from the month because months are zero-based.
function convertToJSONDate(strDate){
var splitted = strDate.split(".");
var newDate = new Date(Date.UTC(splitted[2], (splitted[1] - 1), splitted[0]));
return '/Date(' + newDate.getTime() + ')/';
}
//console.log(convertToJSONDate("10.01.2018"));
//Output: Wed Jan 10 2018 01:00:00 GMT+0100 (Central European Standard Time)
//Output without subtraction: Sat Feb 10 2018 01:00:00 GMT+0100 (Central European Standard Time)
try like this..
#JsonSerialize(using=CustomJsonDateSerializer.class)
#JsonDeserialize(using=CustomJsonDateDeserializer.class)
Related
I have a date in the form of a string like below:
var dateInput= "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
I want to convert this date to dd/mm/yyyy and be able to add and subtract days from this date and still retain the same format.
Here's what I did to convert this string to dd/mm/yyyy date format:
I used this helper function:
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
So, then I did :
var date = new Date(convertDate(eddFromCouch));
which gave me the string 7/12/2019;
Then, when I tried to add the 5 days to the date above, I got the following:
date = date.setDate(date.getDate() + 5);
console.log(date); // returns 1563310800000
I believe 1563310800000 a UNIX timestamp which converts to July,16,2019
I was expecting it to return 12/12/2019.
Here is how you can achieve this using Moment.js. This library makes tasks like parsing, manipulating and displaying dates much easier to achieve.
var input = "2019-08-14T08:06:49.288Z";
var date = moment(input);
date.add(5, "days");
console.log(date.format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Your dateInput is actually the format returned by date.toString, and can be passed directly to the date constructor to get a date object.
function toDDMMYYY(date) {
let parts = [];
let dd = date.getDate();
let mm = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
parts.push(`0${dd}`)
} else {
parts.push(`${dd}`)
}
if (mm < 10) {
parts.push(`0${mm}`)
} else {
parts.push(`${mm}`)
}
parts.push(yyyy)
return parts.join('/');
}
const input = "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
let date = new Date(input);
date = new Date(date.setDate(date.getDate() + 5));
console.log(toDDMMYYY(date))
Hello I want to convert
March 2018 to 032018
in jQuery.I used
var d = new Date($('.selected_month').find("td:first").text());
But it is giving result is:
Thu Mar 01 2018 00:00:00 GMT+0530 (IST)
You need to use getMonth() and getFullYear() on returned date object to format date as per requirement. Also, you need to add 1 to returned month as getMonth method is 0 index based:
(d.getMonth()+1).toString() + d.getFullYear().toString()
Try this
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
return [month,year].join('');
}
Call this function : formatDate('March 2018') // output : 032018
Try converting the date object you end up with to a string:
Try the following snippet, just change var d = new Date() to var d = new Date($('.selected_month').find("td:first").text()).
var d = new Date();
var twoDigitMonth = (d.getUTCMonth() + 1).toString().padStart(2, "0");
var year = d.getUTCFullYear();
var result = twoDigitMonth + year;
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...or try this...
console.log(
new Date("March 2018")
.toLocaleDateString('en-EN', {month: '2-digit',year: 'numeric'})
.replace('/','')
)
If I receive all records from DB with JSON how I can change format 2014-09-04 23:20:00 (this is stored on DB) to 04/09/2014. At the moment date are parsed to Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time)
<script>
$("document").ready(function() {
$.getJSON("test1.php", function(data) {
var table = $("<table>");
$("#div-my-table").empty().append(table);
$.each(data, function(i, item) {
table.append("<tr><td>" + item.code +"</td><td>" + item.line +"</td><td>" + item.org +"</td><td>" + new Date(parseInt(item.by_date.substr("u"))) + "</td></tr>");
});
});
});
</script>
You parse the string, using any of several libraries available for the purpose, and then put it in the format you want, using any of several libraries avaialble for the purpose. On a modern browser, the string you've quoted should be parsed correctly by new Date(), but if you're seeing it not get parsed correctly (your example makes no sense), you may need something like MomentJS.
Or of course, you can regex it:
var yourString = "2014-09-04 23:20:00";
var parts = /^(\d{4})-(\d{2})-(\d{2})/.exec(yourString);
var newString = parts[3] + "/" + parts[2] + "/" + parts[1];
snippet.log("newString = " + newString);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
If you got the values as Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time) means, then do like following
var d=new Date('Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time)');
var day=d.getDate();
var month=d.getMonth()+1;
var year = d.getFullYear();
then format the string like d.getDate()+"/"+(d.getMonth()+1)+"/"+d.getYear()
So you'll get the day, month and year. You can format as the way you want.
You can extract the day, month and year from your Date and then use it to form a string. You can try something as the following:
var dateObj = new Date(jsonDate);
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = day + "/" + month + "/" + year;
alert(newdate);
where jsonDate is the date element you extracted from JSON.
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
alert(d);
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
I want to convert long date format like Sat Dec 13 2014 06:00:00 GMT+0600 to 2014-12-13 yyyy-mm-dd format.
<script>
function myDate(val)
{
var now = new Date("<?php echo $Cnextdue;?>");
now.setDate(now.getDate() + 30*val);
document.getElementById("txtnextdue").value=now;
}
</script>
now variable print in text box as "Sat Dec 13 2014 06:00:00 GMT+0600"
I want to make as 2014-12-13
Use following.
function getDateFormatted(inputdate) {
var k = inputdate;
var dt = new Date(k);
var yr = dt.getYear() + 1900;
var mn = dt.getMonth() + 1;
return yr + "-" + mn + "-" + dt.getDate();
}
alert(getDateFormatted("Sat Dec 13 2014 06:00:00 GMT+0600"));
You can do it by yourself.
But I would suggest you to use Moment.js, so you have more flexibility to change the format in the future if you want.
Using it is as simple as:
moment(new Date()).format("YYYY-MM-DD")
Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!