I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp
Related
How to convert string date to following date format dd-mm-yyyy as a object type in javascript
Ex:
var date='2021-02-23T10:08:44'
var convertedDate='02-23-2021'
The below code works and converts as string '02-23-2021', but because of this I am not able to sort it in UI according to the year,month and date since I am sending it as a string.
let convertedDate = (((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '-' + date.getFullYear().toString().substr(-4));
Here I have more elaborated question:
Sort by last updated entry in descending order as default using react-bootstrap-table-next
You can use this:
var strDate = '2021-02-23T10:08:44'
var convertedDate = new Date(strDate).toLocaleDateString('US').replaceAll('/', '-')
console.log(convertedDate) // 2-23-2021
I have a variable that's returning the following content:
{
"id":1,
"refnumber":3,
"active":false,
"date":"2017-09-14T23:00:00.000Z",
"addons":0,
"age":0
}
If you look at the data field I need a way of changing the data on that field to yyyy-mm-dd.
In other words .. if we take this example as a reference I would need the data field value:
This:
2017-09-14T23:00:00.000Z
To be changed to this:
2017-09-14
How can I do this?
You should just be able to slice away the trailing characters.
data.date = data.date.slice(0, 10);
This works because your data format is in a predictable form where the month and day have a 0 padding.
I recommend a library called momentjs for all your javascript date manipulation needs.
https://momentjs.com/
With it, you can do what you want easily: moment(data.date).format('YYYY-MM-DD')
Note that your JSON is invalid because the date string is not properly quoted, but assuming it's corrected and that your JSON object is named myObject, the following would work:
var date = new Date(myObject.date); //your string will become a date object
//now operate on that date object by extracting the year, month,
//and day into a string
console.log(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
Well you could convert the string to date and then format it
Here is an example
function formate(date) {
if (typeof date == "string")
date = new Date(date);
var day = (date.getDate() <= 9 ? "0" + date.getDate() :
date.getDate());
var month = (date.getMonth() + 1 <= 9 ? "0" +
(date.getMonth() + 1) : (date.getMonth() + 1));
var dateString = day + "-" + month + "-" +
date.getFullYear() + " " + date.getHours() + ":" +
date.getMinutes();
return dateString;
}
I use JS function toLocaleString for date formatting. How can I set one common format for all clients like:
2015-10-29 20:00:00
That I do parsong at PHP by -
I think you would have to manually parse it into that format, which actually isn't too bad. What Date.toLocaleString() returns is a format of:
MM/DD/YYYY, HH:MM:SS
Here's my code snippet to help you out:
// Parse our locale string to [date, time]
var date = new Date().toLocaleString('en-US',{hour12:false}).split(" ");
// Now we can access our time at date[1], and monthdayyear # date[0]
var time = date[1];
var mdy = date[0];
// We then parse the mdy into parts
mdy = mdy.split('/');
var month = parseInt(mdy[0]);
var day = parseInt(mdy[1]);
var year = parseInt(mdy[2]);
// Putting it all together
var formattedDate = year + '-' + month + '-' + day + ' ' + time;
You can set the format as described (yyyy-mm-dd hh:mm:ss) by adding the locale parameter, like this:
toLocaleString("sv-SE")
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
https://www.w3schools.com/Jsref/jsref_tolocalestring.asp
https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
you can use moment.js library which has many features to work with date & time you can easily format a date with that.
here is an example
moment().format('YYYY-MM-DD HH:mm:ss'); // will print in 2015-10-29 20:00:00 format
Moment.js
before doing what i provide please read this and this
var el = document.getElementById('dbg');
var log = function(val){el.innerHTML+='<div><pre>'+val+'</pre></div>'};
var pad = function(val){ return ('00' + val).slice(-2)};
Date.prototype.myFormattedString = function(){
return this.getFullYear() + '-' +
pad( (this.getMonth() + 1) ) + '-' +
pad( this.getDate() ) + ' ' +
pad( this.getHours() ) + ':' +
pad( this.getMinutes() ) + ':' +
pad( this.getSeconds() )
;
}
var curDate = new Date();
log( curDate )
log( curDate.toLocaleString() )
log( curDate.myFormattedString() )
<div id='dbg'></div>
I am using the HTML5 element datetime-local. I need to have two formats of the date. One as a date object the other as a string. I am going to store the date object in the database and I am going to use the string to set the datetime-local form input.
I need to convert this string to a date object:
"2014-06-22T16:01"
I can't seem to get the correct time. This is what I am getting. The time not correct.
Sun Jun 22 2014 09:01:00 GMT-0700 (PDT)
This is the how I am formating the date:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
Example:
http://codepen.io/zerostyle/pen/gwpuK/
If you are trying to get an ISO 8601 date string, you can try Date.prototype.toISOString. However, it always uses UTC. If you want to include the local timezone, use something like the following:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
Edit
The above probably misses your question, which seems to be;
I need to convert this string to a date object: "2014-06-22T16:01"
Presumaly you want to treat it as a local time string. ECMA-262 says that ISO–like strings without a timezone are to be treated as UTC, and that is what your host seems to be doing. So you need a function to create a local Date object from the string:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014
I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');