I have a quastion.
So I get from server a variable with date-time string which looks like this: '31/08/2015 13:24'.
How can extract from this string separately date and time?
You could split the string:
var dateTime = '31/08/2015 13:24'.split(" ");
console.log(dateTime[0]); //date
console.log(dateTime[1]); //time
Or use js Date object to get the day, month, year, hours, etc:
var dateTime = new Date('31/08/2015 13:24');
Related
I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.
I am calling an ajax for getting some values for editing data.
As a part of my object, I am sending the date field.
My problem is that when I receive the date value in the controller, date format is wrong - my dates and months are reversed. And because of that I can't compare them where I need to.
But my months and days are reversed. For an example , instead of 3rd October, it returnes 10th of March.
How to fix this?
I am sending the date field from js in a object like this:
ExamsDataU = {
classId: classIdValue,
date: dateValue
};
And in my controller I tried:
DateTime dateToCheck = Convert.ToDateTime(dto.Date);
The first thing you should know is date parsing with Convert.ToDateTime() depends to the current culture used in server (you may check it using CultureInfo.CurrentCulture property). You can try one of these methods to parse JS date format properly inside controller action method:
1) Using DateTime.ParseExact()/DateTime.TryParseExact() with custom format
On this way it is necessary to specify date format before parsing date:
// specify custom format
string dateFormat = "dd-MM-yyyy";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture);
2) Using DateTime.ParseExact()/DateTime.TryParseExact() with ISO 8601 format
Use date: dateValue.toISOString(); to convert JS date into ISO 8601 format and then convert it:
// specify ISO format
string dateFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
This way is better than the former because no need to write additional date representation code in client-side, also you can adjust date representation to local time if necessary.
Notes:
a) For specified culture, you can try CultureInfo.GetCultureInfo():
var culture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.Name);
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, culture);
b) You can use if condition to check if the date string is valid when using DateTime.TryParseExact():
DateTime dateToCheck;
if (DateTime.TryParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateToCheck))
{
// do something
}
Try this
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
or
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);
console.log(newDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying to remove the Z from the end of a dateTime entity. The timezone of the API gets confused from the site I'm pushing the date from. Does anyone know a script that can remove the Z when a user types in a dateTime?
You're using UTC Date i'm guessing. You can try to use .toLocaleString() on your date time object.
Example
var datetime = new Date();
var now = datetime.toLocaleString();
This should get you something like this: 6/30/2017, 8:47:15 AM
Another option if you want to maintain the format and just remove the T and Z characters is to replace the strings. Example:
var datetime = new Date();
var now = datetime.toISOString().replace('Z', '').replace('T', '');
I am using moment js and new in this. So right now I am getting separated time and date from html to javascript controller so I want to convert into one string with format in moment js.
console.log($scope.timeTo);
console.log($scope.dateTO);
Console OutPut:
04:00
23/05/2017
But I want to set time and date together with momentjs.
Desired format:
2017-05-23T04:00:00
You can simply concat your strings and then parse it with moment.
Then you can use format() to get moment object in the format you need.
var timeTo = '04:00';
var dateTo = '23/05/2017';
var m = moment(dateTo + timeTo, 'DD/MM/YYYY HH:mm');
console.log(m.format('YYYY-MM-DD[T]HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
I have this application where I want to use you date, but the problem is that the date is not working as I expect.
I create a date object like this:
// Get today's date
today: function () {
// Create a new date
var date = new Date();
// Set to midnight
date.setHours(0, 0, 0, 0);
// Return our date
return date;
},
and If I output that date in my view I get yesterdays date at 23:00 hours....
Which looks like this:
2015-07-08T23:00:00.000Z
Does anyone know how I can get the date to be formatted properly?
Update
Just to elaborate a bit, I want to use the date to compare against records in the database. These records have the date applied to them, because the JavaScript is showing the local date time, it is not comparing correctly. Also there is a case where I am saving that date and I don't want it to save the local date.
based on your culture setting you can use the
date.toLocaleDateString()
this will give localized string format back
date.toUTCString();
date.toLocaleString();
date.toLocaleDateString();
date.toDateString();
date.toISOString();
Find your answer here :) And the best option is to use momentjs http://momentjs.com/
So, I ended up creating this function:
// Converts a date to a timeStamp
this.convertToTimeStamp = function (dateTime) {
// Get just the date
var date = dateTime.toDateString();
// Get the timestamp
var timeStamp = Date.parse(date);
// Return our timeStamp
return timeStamp;
};
If my understanding is correct, that should create the same date no matter what timezone / locale you are in.