Date and time based json element using javascript - javascript

I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?

Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)

JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!

Related

Getting same unix time stamp for two different times in javascript

I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
var date = new Date(date_string);
return date.getTime() / 1000;
}
This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
var year = ics_string.slice(0, 4);
var month = ics_string.slice(4, 6);
var date = ics_string.slice(6, 8);
var hours = ics_string.slice(9, 11);
var minutes = ics_string.slice(11, 13);
var seconds = ics_string.slice(13, 15);
var milliseconds = 0;
console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}
Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example
Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
var year = parseInt(ics_string.slice(0, 4));
var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
var date = parseInt(ics_string.slice(6, 8));
var hours = parseInt(ics_string.slice(9, 11));
var minutes = parseInt(ics_string.slice(11, 13));
var seconds = parseInt(ics_string.slice(13, 15));
return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}
I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.

UTC date convert to local timezone

I have a date in UTC format.
"2016-10-12 05:03:51"
I made a function to convert UTC date to my local time.
function FormatDate(date)
{
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
My Local timezone is GMT +0530.
My code produced this output:
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)
I converted the date with an online tool to get the correct date and time.
Wednesday, October 12, 2016 10:30 AM
My code matches the online tool on time but not on date.
How can I correct my code's output, preferably using moment.js?
UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"
You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.
function parseDateUTC(s){
var arr = s.split(/\D/);
return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}
console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());
If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:
var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>
Since you have tagged moment, I'm assuming you are using moment.
In such cases, you should keep your approach consistent and not mix moment and date object.
var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)
console.log(date.toString())

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this
var d='dd/mm/yy hh:MM:ss';
var d1=d.split(" ");
var date=d1[0].split("/");
var time=d1[1].split(":");
var dd=date[0];
var mm=date[1]-1;
var yy=date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];
var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);
Is there Any way to do it using JQuery OR JavaScript?
If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:
let dtStr = "12/03/2010 09:55:35"
console.log(strToDate(dtStr)); // Fri Mar 12 2010 09:55:35
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
How about Date.parse()?
new Date( Date.parse("05/12/05 11:11:11") );
// Thu May 12 2005 11:11:11 GMT+0200 (CEST)
The output produced is in local timezone and will differ in browsers in different timezones.
We can convert any local date format to datetime datatype using moment js.
Syntax:
moment('<local date value>','<local date format>').format('<expected convert format>')
Example:
moment('26/05/1986 00:00', 'DD/MM/YYYY HH:mm').format("MM/DD/YYYY HH:mm");
then the output will be 05/26/1986 00:00
Cheers
Date#parse should be able to parse that if you split on a string. Id also recommend looking into the npm package moment for date manipulation
From your code it seems that you are trying to convert string into date and also you are trying to fetch previous month. If yes then you can reconstruct your code as below:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
return d;
}
$(document).ready(function() {
var dateString='2015-06-17T18:30:12';
var d = new Date(dateString);
alert(d.SubtractMonth(1));
});

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31

Add Number of months to a Date in a text field

function addDays(){
var myDate =document.getElementById('treatdate');
var numberOfDaysToAdd = document.getElementById('resultdays');
var tset = numberOfDaysToAdd.value;
var result1 = myDate.value.addMonths(parseInt(tset));
var pldate= moment(result1).format('YYYY-MM-DD');
return pldate; }
'treatdate' is an id for a treatment date which is pulled from my database. Thanks in advance.
You can always use moment.js library for Date manipulations. http://momentjs.com/
For your problem you can do the following.
function addDays(){
var datefrmDb = $('#treatdate').val();
var monthstoadd= $('#resultdays').val();
var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
return new_date;
}
If your date format is yyyy-MM-dd
var myDate = new Date(document.getElementById('treatdate').value);
this will a date and time.
Example:
var dd = new Date("2014-02-02 11:11:11")
console log
Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)
See if this snippet can help you understand how to manipulate dates. To change/add the months to a Date() object you can use the setMonth() method.
numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months
Note that you may add numbers beyond 12 - the object handles the date, and jumps to the next year.

Categories

Resources