I am receiving a form value for date in Kendo Datepicker. It comes in as an object.
1)
How do I convert the following to date?
The following in Debugger still left it as Object
new Date(this.editHeaderAddressForm.value.seasonalEnd);
2) Additionally, how can I convert it to Moment?
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
var newDate = Date('December 17, 1995 03:24:00');
console.log(javaScriptRelease);
> // expected output: 818035920000
console.log(newDate);
> // expected output: Sun Dec 17 1995 03:24:00 GMT...
You can get date, and moment with short and simple code.
var full_time = new Date(this.editHeaderAddressForm.value.seasonalEnd);
var date = full_time.toLocaleDateString();
var moment = full_time.toLocaleTimeString();
console.log(date);
console.log(moment);
Use Date.parse method
const epochValue = Date.parse(this.editHeaderAddressForm.value.seasonalEnd);
This will return date in EPOCH this you can directly pass in to Moment function as well.
moment.unix(epochValue)
Related
Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?
I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()
The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)
The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:
// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
let [Y, M, D] = s.split(/\W/);
return new Date(Y, M-1, D);
}
console.log(parseISOLocal('2021-07-20').toString());
This is a very common issue.
Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.
// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)
Using Moment.js
const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");
Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]
console.log(previousDayString)
In my html file I'm passing an array of objects with a date time to javascript like this
<script>
var TimerEvents = #Html.Raw(Json.Encode(Model.PendingTimerEvents));
</script>
my 'TimerEvents' has an EventTime property that when I read in Javascript looks like this
"/Date(1521617700000)/"
and I want to get this value, whatever it is, into a Javascript Date() object.
like this
var countDownDate = new Date(date here).getTime();
What is that format, and how would I do this?
the value you get is a milisecond representation of the date, I think the count starts at 1/1/1970.
Anyway here is a solution for formatting it:
Converting milliseconds to a date (jQuery/JavaScript)
Assuming that Model.PendingTimerEvents is a DateTime, you could just do:
var TimerDate = new Date(#Model.PendingTimerEvents.Year, #Model.PendingTimerEvents.Month, #Model.PendingTimerEvents.Day, #Model.PendingTimerEvents.Hour, #Model.PendingTimerEvents.Minute, #Model.PendingTimerEvents.Second);
You can extract the date with regex if you need to:
<script>
var TimerEvents = #Html.Raw(Json.Encode(Model.PendingTimerEvents)); //"/Date(1521617700000)/"
var dateString = TimerEvents.match(/\d+/)[0] // "1521617700000"
var date = new Date(+dateString); //convert to number
console.log(date); // Wed Mar 21 2018 08:35:00 GMT+0100 (Mitteleuropäische Zeit)
</script>
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())
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));
});
I created some funtion but how to convert string timestamp to date format for the given variabe.
var data="/Date(1424853425207)/";
data=data.parse(data);
consoe.log(data);
But enabe show the date for the above variable
You can fetch the timestamp using regex and then cast to a number so it can be used to create a new instance of Date:
var data = "/Date(1424853425207)/";
var timestamp = +data.replace(/\/Date\((.*?)\)\//g, '$1');
var date = new Date(timestamp);
console.log(date); // Wed Feb 25 2015 09:37:05 GMT+0100